📖 Scenario: You are working on a simple banking application that uses MongoDB to store account information. You want to ensure that when multiple operations happen at the same time, the data stays consistent and isolated. This means if one transaction is updating an account balance, another transaction should not see partial changes until the first one is complete.
🎯 Goal: Build a MongoDB transaction that updates two accounts' balances atomically, demonstrating transaction isolation. You will create the initial data, configure the session, perform the transaction with updates, and then commit the transaction.
📋 What You'll Learn
Create a collection called accounts with two documents having _id and balance fields.
Start a client session and assign it to a variable called session.
Use session.startTransaction() to begin the transaction.
Update the balances of both accounts inside the transaction using updateOne with the session option.
Commit the transaction using session.commitTransaction().
💡 Why This Matters
🌍 Real World
Transactions ensure that complex operations like money transfers happen safely without data corruption or partial updates.
💼 Career
Understanding MongoDB transactions and isolation is important for backend developers working with databases that require data consistency and atomic operations.
Progress0 / 4 steps
1
Create the initial accounts collection with two documents
Create a collection called accounts and insert exactly two documents: one with _id of 1 and balance of 500, and another with _id of 2 and balance of 300.
MongoDB
Hint
Use insertMany on db.accounts with an array of two objects.
2
Start a client session for the transaction
Create a client session and assign it to a variable called session using db.getMongo().startSession().
MongoDB
Hint
Use db.getMongo().startSession() and assign it to session.
3
Start the transaction and update account balances
Use session.startTransaction() to begin the transaction. Then update the account with _id 1 by subtracting 100 from balance, and update the account with _id 2 by adding 100 to balance. Use updateOne with the session option for both updates.
MongoDB
Hint
Call session.startTransaction() first. Then use db.accounts.updateOne twice with the session option to update balances.
4
Commit the transaction to finalize changes
Commit the transaction by calling session.commitTransaction().
MongoDB
Hint
Call session.commitTransaction() to save the changes made in the transaction.
Practice
(1/5)
1. What does transaction isolation in MongoDB primarily ensure?
easy
A. Data consistency when multiple operations happen at the same time
B. Faster query execution
C. Automatic data backup
D. Unlimited storage capacity
Solution
Step 1: Understand transaction isolation purpose
Transaction isolation ensures that concurrent operations do not interfere and cause inconsistent data.
Step 2: Relate to MongoDB transactions
MongoDB uses transaction isolation to keep data consistent when many changes happen simultaneously.
Final Answer:
Data consistency when multiple operations happen at the same time -> Option A
Quick Check:
Transaction isolation = Data consistency [OK]
Hint: Transaction isolation means safe, consistent data changes [OK]
Common Mistakes:
Confusing isolation with performance improvements
Thinking it automatically backs up data
Assuming it increases storage
2. Which of the following is the correct way to start a transaction in MongoDB using a session?
easy
A. session.startTransaction()
B. db.startTransaction()
C. transaction.begin()
D. session.beginTransaction()
Solution
Step 1: Recall MongoDB transaction syntax
In MongoDB, transactions start on a session object using startTransaction().
Step 2: Check each option
Only session.startTransaction() is the correct method; others are invalid or do not exist.
A. Missing await before session.commitTransaction()
B. Using session.beginTransaction() instead of session.startTransaction()
C. Not passing session to updateOne()
D. Calling session.endSession() too early
Solution
Step 1: Check transaction start method
MongoDB sessions use startTransaction(), not beginTransaction(). Using beginTransaction() causes an error.
Step 2: Verify other parts
Await is correctly used before commitTransaction(), session is passed to updateOne(), and endSession() is called after commit.
Final Answer:
Using session.beginTransaction() instead of session.startTransaction() -> Option B
Quick Check:
Correct method is startTransaction() [OK]
Hint: Use startTransaction(), not beginTransaction() [OK]
Common Mistakes:
Using beginTransaction() which does not exist
Forgetting to pass session in operations
Calling endSession() before commit
5. You want to ensure that two related updates in MongoDB either both succeed or both fail to keep data consistent. Which approach best achieves this using transaction isolation?
hard
A. Perform both updates separately without a transaction
B. Use findOneAndUpdate without transactions
C. Use a session and start a transaction to group both updates, then commit or abort together
D. Run updates in parallel without session
Solution
Step 1: Understand transaction purpose
Transactions group multiple operations so they succeed or fail as one unit, ensuring consistency.
Step 2: Apply MongoDB transaction usage
Using a session with startTransaction(), performing updates, then commit or abort ensures atomicity and isolation.
Step 3: Evaluate other options
Performing updates separately or in parallel without transactions risks partial success and inconsistent data.
Final Answer:
Use a session and start a transaction to group both updates, then commit or abort together -> Option C
Quick Check:
Group updates in transaction = consistency [OK]
Hint: Group related changes in a transaction session [OK]
Common Mistakes:
Updating separately risking partial failure
Not using sessions for transactions
Assuming findOneAndUpdate is atomic across multiple operations
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.