0
0
MongoDBquery~30 mins

Transaction isolation in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Transaction Isolation in MongoDB
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Call session.commitTransaction() to save the changes made in the transaction.