0
0
MongoDBquery~30 mins

Transaction performance considerations in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Transaction Performance Considerations in MongoDB
📖 Scenario: You are managing a small online bookstore database using MongoDB. You want to understand how to handle transactions efficiently to keep the system fast and reliable when multiple users buy books at the same time.
🎯 Goal: Build a simple MongoDB transaction that updates the stock of books and records the sale, while considering performance best practices.
📋 What You'll Learn
Create a collection called books with sample book documents
Create a collection called sales to record purchases
Set a transaction option with a write concern for performance
Write a transaction that updates book stock and inserts a sale record
💡 Why This Matters
🌍 Real World
Online stores and inventory systems use transactions to keep stock counts accurate and sales records consistent when many users buy items at the same time.
💼 Career
Understanding transaction performance helps database administrators and backend developers build fast, reliable applications that handle concurrent data changes safely.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a collection called books and insert these exact documents: { _id: 1, title: "Learn MongoDB", stock: 10 } and { _id: 2, title: "Mastering NoSQL", stock: 5 }.
MongoDB
Need a hint?

Use insertMany to add multiple documents to the books collection.

2
Create the sales collection
Create an empty collection called sales to store purchase records.
MongoDB
Need a hint?

Use createCollection to make the sales collection.

3
Set transaction options for performance
Create a variable called transactionOptions and set it to an object with writeConcern set to { w: "majority" } to ensure data is written reliably but efficiently.
MongoDB
Need a hint?

Set transactionOptions with writeConcern to { w: "majority" }.

4
Write a transaction to update stock and record a sale
Write a transaction function called buyBook that takes bookId and quantity. Inside the transaction, update the stock of the book by subtracting quantity and insert a sale document into sales with bookId and quantity. Use transactionOptions when starting the transaction.
MongoDB
Need a hint?

Use startSession() to begin a session, then startTransaction(transactionOptions). Update the book stock only if enough stock exists, insert the sale, then commit or abort the transaction.