📖 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
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
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
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
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.
Practice
(1/5)
1. What is a key reason to use transactions in MongoDB?
easy
A. To keep data changes safe and consistent
B. To speed up query execution
C. To reduce disk space usage
D. To avoid indexing
Solution
Step 1: Understand the purpose of transactions
Transactions ensure that multiple related data changes happen together or not at all, keeping data consistent.
Step 2: Identify the correct purpose
Speeding up queries, reducing disk space, or avoiding indexing are not the main reasons for transactions.
Final Answer:
To keep data changes safe and consistent -> Option A
Quick Check:
Transactions = Data safety and consistency [OK]
Hint: Transactions ensure data safety, not speed [OK]
Common Mistakes:
Thinking transactions speed up queries
Confusing transactions with indexing
Believing transactions reduce disk space
2. Which of the following is the correct way to start a transaction in MongoDB using the shell?
easy
A. transaction.begin()
B. db.startTransaction()
C. startTransaction()
D. session.startTransaction()
Solution
Step 1: Recall MongoDB transaction syntax
Transactions are started on a session object using session.startTransaction().
Step 2: Check other options
db.startTransaction() and startTransaction() are invalid commands. transaction.begin() is not a MongoDB method.
What is the main issue causing the transaction to fail?
medium
A. session.endSession() should be called before commitTransaction()
B. commitTransaction() must be called before startTransaction()
C. The insertOne operation is missing the session option
D. Transactions cannot include insertOne operations
Solution
Step 1: Check transaction usage in code
The insertOne call does not include the session option, so it runs outside the transaction.
Step 2: Understand transaction requirements
All operations inside a transaction must specify the session to be part of it. Without it, commitTransaction has no effect on that operation.
Final Answer:
The insertOne operation is missing the session option -> Option C
Quick Check:
Missing session in operation = transaction fails [OK]
Hint: Include session option in all operations inside transactions [OK]
Common Mistakes:
Calling commitTransaction before startTransaction
Ending session before committing
Thinking insertOne can't be in transactions
5. Which practice helps improve transaction performance in MongoDB when working with many documents?
hard
A. Keep transactions short and avoid long-running operations
B. Use transactions for every single write operation
C. Avoid using indexes inside transactions
D. Run multiple transactions in parallel on the same documents
Solution
Step 1: Understand transaction performance impact
Long transactions hold locks and resources longer, slowing performance and increasing conflicts.
Step 2: Identify best practice
Keeping transactions short reduces lock time and improves throughput. Using transactions for every write or running parallel conflicting transactions harms performance. Indexes improve query speed and are not avoided.
Final Answer:
Keep transactions short and avoid long-running operations -> Option A
Quick Check:
Short transactions = better performance [OK]
Hint: Keep transactions short to boost speed and reduce conflicts [OK]
Common Mistakes:
Using transactions for every write unnecessarily
Avoiding indexes inside transactions
Running conflicting transactions in parallel
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.