Multi-Document Transactions — MongoDB Technical Interview Questions & Answers
ACID transactions across multiple documents/collections.
Multi-Document Transactions
- Simple meaning: A transaction makes several writes all succeed or all fail. MongoDB supports multi-document transactions on replica sets (4.0+).
- How to use: session.startTransaction(); two updateOne with { session }; commit or abort. Drivers show this; mongosh can too.
- Single-document writes are already atomic — you do not need a transaction to $set two fields on Asha.
- Common mistake: wrapping every insert in a transaction. Extra cost. Atlas M0 may have limits — check current docs.
- Interview tip: “Document atomic by default. Multi-doc transactions exist; use for money-like transfers.”
Technical Interview Tip: When do you actually need a transaction?
Code Examples for Multi-Document Transactions
Multi-Document Transactions — working example
// mongosh / driver-style multi-document transaction (replica set / mongos required)
session = db.getMongo().startSession()
session.startTransaction()
try {
const users = session.getDatabase("prep_pilot").users
const accounts = session.getDatabase("prep_pilot").accounts
users.updateOne({ email: "ada@example.com" }, { $inc: { points: -10 } })
accounts.updateOne({ email: "ada@example.com" }, { $inc: { balance: 10 } })
session.commitTransaction()
} catch (e) {
session.abortTransaction()
throw e
} finally {
session.endSession()
}Multi-Document Transactions — multi-document ACID transactions need a replica set (or sharded cluster) and a session.
How to Explain Multi-Document Transactions to an Interviewer
Are MongoDB writes atomic?
Yes for one document Multi-document needs a transaction