📖 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 and the order is recorded together. This means both actions must happen at the same time or not at all to keep data correct.
🎯 Goal: Build a MongoDB script that uses a session and a transaction to update the stock quantity of a book and insert a new order document atomically.
📋 What You'll Learn
Create a session using client.startSession()
Start a transaction with session.startTransaction()
Update the books collection to reduce stock by 1 inside the transaction
Insert a new document into the orders collection inside the transaction
Commit the transaction with session.commitTransaction()
End the session with session.endSession()
💡 Why This Matters
🌍 Real World
Transactions ensure that multiple related database changes happen together, preventing data errors in real-world apps like online stores or banking.
💼 Career
Understanding MongoDB sessions and transactions is important for backend developers working with NoSQL databases to maintain data integrity.
Progress0 / 4 steps
1
Setup MongoDB client and collections
Create a MongoDB client variable called client connected to 'mongodb://localhost:27017'. Then create variables books and orders for the collections 'books' and 'orders' in the database 'bookstore'.
MongoDB
Hint
Use new MongoClient('mongodb://localhost:27017') to create the client. Use client.db('bookstore').collection('books') to get the books collection.
2
Start a session and transaction
Create a session variable called session by calling client.startSession(). Then start a transaction on this session using session.startTransaction().
MongoDB
Hint
Call client.startSession() and assign it to session. Then call session.startTransaction().
3
Perform update and insert inside the transaction
Inside the transaction, use books.updateOne() with { title: 'Learn MongoDB' } filter and { $inc: { stock: -1 } } update. Pass the session option. Then insert a new order document { bookTitle: 'Learn MongoDB', quantity: 1 } into orders collection with the same session option.
MongoDB
Hint
Use books.updateOne() with the filter and update objects, passing { session } as options. Then use orders.insertOne() with the new order document and the same session option.
4
Commit transaction and end session
Commit the transaction by calling session.commitTransaction(). Then end the session by calling session.endSession().
MongoDB
Hint
Call session.commitTransaction() to save changes, then session.endSession() to finish.
Practice
(1/5)
1. What is the main purpose of using startSession() in MongoDB?
easy
A. To commit changes to the database
B. To begin a session that groups operations for transactions
C. To abort a running transaction
D. To create a new database
Solution
Step 1: Understand the role of sessions
Sessions in MongoDB group multiple operations so they can be executed as a single unit.
Step 2: Identify what startSession() does
This method starts a new session to enable transactions or grouped operations.
Final Answer:
To begin a session that groups operations for transactions -> Option B
Quick Check:
startSession() starts a session [OK]
Hint: Sessions group operations; startSession() begins it [OK]
Common Mistakes:
Confusing startSession() with commitTransaction()
Thinking startSession() commits or aborts transactions
Assuming startSession() creates a database
2. Which of the following is the correct syntax to start a transaction in a MongoDB session named session?
easy
A. session.beginTransaction()
B. session.transactionStart()
C. session.startTransaction()
D. session.openTransaction()
Solution
Step 1: Recall the MongoDB transaction method
The correct method to start a transaction on a session object is startTransaction().
Step 2: Check each option's syntax
Only session.startTransaction() matches the official MongoDB API.
Final Answer:
session.startTransaction() -> Option C
Quick Check:
startTransaction() starts transactions [OK]
Hint: Use startTransaction() to begin transactions on sessions [OK]
Common Mistakes:
Using beginTransaction() which is not a MongoDB method
Mixing method names like transactionStart()
Using openTransaction() which does not exist
3. Given the following code snippet, what will be the output if the transaction commits successfully?
B. startSession() should be called after startTransaction()
C. commitTransaction() should be called before insertOne
D. endSession() should be called before commitTransaction()
Solution
Step 1: Review transaction usage in operations
Operations inside a transaction must include the session option to be part of it.
Step 2: Check the insertOne call
The insertOne call lacks the {session} option, so it is not part of the transaction.
Final Answer:
Missing session option in insertOne operation -> Option A
Quick Check:
Operations need {session} to join transaction [OK]
Hint: Include {session} in operations inside transactions [OK]
Common Mistakes:
Calling startSession() after startTransaction()
Calling commitTransaction() before operations
Ending session before committing transaction
5. You want to ensure that either all writes in a batch succeed or none do in MongoDB. Which sequence of commands correctly implements this using sessions and transactions?
All operations must be inside a started transaction and include the session option.
Step 2: Evaluate each option
const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.commitTransaction(); session.endSession(); correctly starts a session, starts a transaction, performs writes with session, commits, and ends session. Others either miss session in operations, start transaction late, or abort instead of commit.