0
0
MongoDBquery~30 mins

Session and transaction syntax in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Sessions and Transactions in MongoDB
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Call session.commitTransaction() to save changes, then session.endSession() to finish.