📖 Scenario: You are managing a simple banking system where users can transfer money between accounts. Each account is stored as a document in a MongoDB collection. To keep the data consistent, you need to update both the sender's and receiver's account balances in a single transaction.
🎯 Goal: Build a multi-document transaction in MongoDB that safely transfers money from one account to another, ensuring both accounts are updated together or not at all.
📋 What You'll Learn
Create two account documents with specific balances
Set up a MongoDB session for transactions
Write a transaction that deducts money from one account and adds it to another
Commit the transaction to save changes atomically
💡 Why This Matters
🌍 Real World
Banking and financial applications require multi-document transactions to keep account balances consistent during transfers.
💼 Career
Understanding MongoDB transactions is important for backend developers working with NoSQL databases to ensure data integrity.
Progress0 / 4 steps
1
Create the accounts collection with two account documents
Create a MongoDB collection called accounts and insert two documents with these exact fields and values: { _id: 1, name: "Alice", balance: 500 } and { _id: 2, name: "Bob", balance: 300 }.
MongoDB
Hint
Use insertMany on the accounts collection to add both documents at once.
2
Start a client session for the transaction
Create a variable called session by starting a client session using client.startSession().
MongoDB
Hint
Use client.startSession() to create a session for transactions.
3
Write the transaction to transfer money
Use session.withTransaction() to run a transaction function that deducts 100 from Alice's balance and adds 100 to Bob's balance using updateOne with { $inc: { balance: -100 } } and { $inc: { balance: 100 } } respectively. Use session as an option in both updates.
MongoDB
Hint
Inside withTransaction, use updateOne twice with the session option to update both accounts.
4
End the session after the transaction
Call session.endSession() to properly close the client session after the transaction.
MongoDB
Hint
Always call endSession() to close the session after finishing the transaction.
Practice
(1/5)
1. What is the main purpose of using multi-document transactions in MongoDB?
easy
A. To create indexes automatically
B. To speed up single document queries
C. To ensure multiple document changes succeed or fail together
D. To backup the database
Solution
Step 1: Understand transaction purpose
Transactions group multiple operations so they either all succeed or all fail, ensuring data consistency.
Step 2: Compare options
Only To ensure multiple document changes succeed or fail together describes this behavior. Other options describe unrelated features.
Final Answer:
To ensure multiple document changes succeed or fail together -> Option C
Quick Check:
Transaction purpose = group changes atomically [OK]
Hint: Transactions group multiple changes to keep data consistent [OK]
Common Mistakes:
Confusing transactions with indexing
Thinking transactions speed up single queries
Assuming transactions create backups
2. Which of the following is the correct way to start a transaction in a MongoDB session using the Node.js driver?
easy
A. db.transactionStart()
B. session.startTransaction()
C. session.begin()
D. start.sessionTransaction()
Solution
Step 1: Recall MongoDB transaction syntax
The correct method to start a transaction on a session is startTransaction().
Step 2: Eliminate incorrect options
Options A, B, and D are not valid MongoDB session methods.
B. session.endSession() should be called before commitTransaction()
C. session.startSession() should be awaited
D. Missing parentheses on startTransaction; use session.startTransaction()
Solution
Step 1: Identify the syntax error
The code calls session.startTransaction without parentheses, so the function is not executed.
Step 2: Correct the method call
Add parentheses to call the function: session.startTransaction().
Final Answer:
Missing parentheses on startTransaction; use session.startTransaction() -> Option D
Quick Check:
Method calls need parentheses () [OK]
Hint: Always add () to call methods like startTransaction() [OK]
Common Mistakes:
Forgetting parentheses on method calls
Calling endSession before commitTransaction
Thinking startSession is async and needs await
5. You want to update two collections atomically: deduct 10 from accounts.balance and add 10 to transactions.amount. Which transaction code snippet correctly ensures both updates succeed or fail together?