Mid
From PDF
SQL
SQL & Databases
How does MongoDB handle transactions and what are the transaction capabilities?
Short answer: MongoDB provides multi-document transactions starting with version 4.0. This allows you to execute multiple operations in a transaction, ensuring ACID properties (Atomicity, Consistency, Isolation, Durability) across multiple documents and collections.
Example code
const session = client.startSession(); try { session.startTransaction(); db.collection1.updateOne({ _id: 1 }, { $set: { status: "completed" } }, { session }); db.collection2.updateOne({ _id: 2 }, { $set: { status: "shipped" } }, { session }); session.commitTransaction(); } catch (error) { session.abortTransaction(); } finally { session.endSession(); }
Real-world example (ShopNest)
Checkout wraps stock decrement + order insert in a transaction so you never sell stock you do not have.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png