📖 Scenario: You are managing a small online bookstore database. You want to ensure that when a customer places an order, the stock quantity is updated only if the order is successfully recorded. If anything goes wrong, no changes should be saved.
🎯 Goal: Build a MongoDB transaction that inserts a new order and updates the stock quantity of a book. If any step fails, the transaction should abort, leaving the database unchanged.
📋 What You'll Learn
Create a MongoDB collection named books with a document for a book titled 'Learn MongoDB' with stock quantity 10.
Create a MongoDB collection named orders to store customer orders.
Start a session and a transaction.
Insert a new order document with customer name 'Alice' and book title 'Learn MongoDB'.
Update the stock quantity of 'Learn MongoDB' by reducing it by 1.
Commit the transaction if all operations succeed.
Abort the transaction if any operation fails.
💡 Why This Matters
🌍 Real World
Transactions ensure that multiple related database operations either all succeed or all fail, which is critical for applications like online stores to keep data consistent.
💼 Career
Understanding commit and abort behavior in MongoDB transactions is essential for backend developers and database administrators working with modern NoSQL databases.
Progress0 / 4 steps
1
Create the initial books collection with one book document
Create a MongoDB collection called books and insert one document with { title: 'Learn MongoDB', stock: 10 }.
MongoDB
Hint
Use insertOne on the books collection with the specified document.
2
Create the orders collection and start a session
Create a MongoDB collection called orders and start a client session with const session = db.getMongo().startSession().
MongoDB
Hint
Use db.createCollection('orders') to create the orders collection and db.getMongo().startSession() to start a session.
3
Start a transaction and insert an order document
Use session.startTransaction() to begin a transaction. Then insert a document { customer: 'Alice', book: 'Learn MongoDB' } into the orders collection using the session.
MongoDB
Hint
Call startTransaction() on the session, then insert the order document passing { session } as an option.
4
Update stock and commit or abort the transaction
Update the books collection to reduce the stock of 'Learn MongoDB' by 1 using the session. Then commit the transaction with session.commitTransaction(). If an error occurs, abort the transaction with session.abortTransaction().
MongoDB
Hint
Use updateOne with $inc to reduce stock, then commit or abort the transaction inside a try-catch block.
Practice
(1/5)
1. What happens when you commit a transaction in MongoDB?
easy
A. All changes made during the transaction are saved permanently.
B. All changes made during the transaction are discarded.
C. The transaction is paused and can be resumed later.
D. Only some changes are saved, others are lost.
Solution
Step 1: Understand commit behavior
Committing a transaction means saving all changes made during that transaction permanently to the database.
Step 2: Compare with abort
Unlike abort, which cancels changes, commit finalizes them.
Final Answer:
All changes made during the transaction are saved permanently. -> Option A
Quick Check:
Commit = Save changes [OK]
Hint: Commit means save all changes made in the transaction [OK]
Common Mistakes:
Confusing commit with abort
Thinking commit only saves some changes
Believing commit pauses the transaction
2. Which of the following is the correct syntax to abort a transaction in MongoDB using the shell?
easy
A. transaction.abort()
B. session.abortTransaction()
C. db.abort()
D. session.commit()
Solution
Step 1: Recall MongoDB transaction abort syntax
The correct method to abort a transaction is session.abortTransaction().
Step 2: Eliminate incorrect options
session.commit() is invalid, db.abort() and transaction.abort() are not valid MongoDB shell commands.
D. endSession() must be called before commitTransaction()
Solution
Step 1: Check async calls in transaction
commitTransaction() returns a promise and must be awaited to complete properly.
Step 2: Identify missing await causes error
Without await, the code may proceed before commit finishes, causing errors.
Final Answer:
Missing await before commitTransaction() -> Option C
Quick Check:
Async commit needs await [OK]
Hint: Always await commitTransaction() to avoid errors [OK]
Common Mistakes:
Not awaiting commitTransaction()
Calling startTransaction() multiple times
Calling endSession() too early
5. You want to update two documents atomically in MongoDB. You start a transaction, update the first document, then update the second. If the second update fails, what should you do to ensure no partial changes remain?
hard
A. Manually delete the first update after failure.
B. Commit the transaction to save the first update only.
C. Ignore the failure and continue.
D. Abort the transaction to cancel all changes.
Solution
Step 1: Understand atomicity in transactions
Transactions ensure all-or-nothing changes. If one update fails, the whole transaction should be canceled.
Step 2: Apply abort to cancel partial changes
Aborting the transaction cancels all changes, preventing partial updates.
Final Answer:
Abort the transaction to cancel all changes. -> Option D
Quick Check:
Fail in transaction = abort all changes [OK]
Hint: Abort transaction to avoid partial updates on failure [OK]
Common Mistakes:
Committing partial updates
Trying to manually fix partial changes
Ignoring failure and continuing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.