Does MongoDB support transactions?
IntermediateConceptMongoDB
Answer
Short answer
Yes. Single-document operations have always been atomic, and since MongoDB 4.0 (replica sets) and 4.2 (sharded clusters) it supports multi-document ACID transactions. They're useful when several documents must change together, but they add overhead — good schema design (embedding) avoids most of the need.
Example
const session = db.getMongo().startSession();
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } });
try {
const accounts = session.getDatabase("bank").accounts;
accounts.updateOne({ _id: 1 }, { $inc: { balance: -500 } });
accounts.updateOne({ _id: 2 }, { $inc: { balance: 500 } });
session.commitTransaction();
} catch (e) {
session.abortTransaction(); throw e;
} finally { session.endSession(); }
Things to know
- Requires a replica set (even a single-node one) — not a standalone server.
- Default time limit: 60 seconds per transaction.
- Keep transactions short; they hold resources and can conflict.
What to say in the interview
"Single-document writes are atomic by design, and multi-document ACID transactions exist since 4.0 on replica sets. We use them for things like transfers, keep them short, and prefer embedding so most updates stay within one document."