Since MongoDB 4.0, multi-document ACID transactions on replica sets mirror SQL BEGIN/COMMIT for critical flows.
Session transaction (mongosh)
session = db.getMongo().startSession()
session.startTransaction()
try {
const orders = session.getDatabase('practice').orders
const inventory = session.getDatabase('practice').inventory
orders.insertOne({ sku: 'A1', qty: 1 }, { session })
inventory.updateOne({ sku: 'A1' }, { $inc: { stock: -1 } }, { session })
session.commitTransaction()
} catch (e) {
session.abortTransaction()
throw e
} finally {
session.endSession()
}Practice: Concepts apply to Atlas and self-hosted; try read-only commands in mongosh where safe.
When to use
Inventory + order creation, wallet transfers—prefer single-document atomicity when possible; transactions add latency and require replica set.
Important interview questions and answers
- Q: Replica set requirement?
A: Transactions need replication protocol—standalone dev converts to RS for testing. - Q: Retry on transient errors?
A: Drivers retry commit on UnknownTransactionCommitResult—design idempotent ops.
Self-check
- Why prefer single-doc atomicity?
- What does abortTransaction do?
Tip: Prefer single-document atomic updates when they satisfy the business rule.
Interview prep
- Replica set?
- Transactions require replica set deployment.
- abortTransaction?
- Rolls back uncommitted changes in session.