What are MongoDB transactions and when should you use them?
Learn how MongoDB multi-document transactions give ACID guarantees, when to use them versus atomic single-document writes, and how to run them safely.
Expected Interview Answer
MongoDB transactions let you group multiple read and write operations across one or more documents and collections into a single all-or-nothing unit that either commits entirely or rolls back entirely, giving you ACID guarantees.
Because a single document write is already atomic in MongoDB, transactions are only needed when a business operation must keep several documents consistent at once — for example moving money between two accounts. Multi-document transactions require a replica set or sharded cluster, are started from a client session, and hold locks and a snapshot for their duration, so they add overhead and should be used deliberately rather than by default.
- All-or-nothing atomicity across many documents and collections
- Snapshot isolation so reads inside the transaction see a consistent view
- Automatic rollback on error or abort
- Preserves invariants like balanced debits and credits
- Familiar ACID semantics for developers coming from relational databases
AI Mentor Explanation
A transaction is like a completed over in cricket: all six legal deliveries must be recorded together for the over to count. If the over is abandoned midway due to rain, the whole over is scrubbed and the score reverts — you never leave three balls half-counted. A multi-document transaction commits all its writes as one over or rolls every one back.
Step-by-Step Explanation
Step 1
Start a session
Obtain a client session with startSession(), which anchors the transaction context.
Step 2
Begin the transaction
Call session.startTransaction() with optional read and write concern settings.
Step 3
Run operations with the session
Pass the session to every operation so all reads and writes belong to the transaction.
Step 4
Commit or abort
Call commitTransaction() on success, or abortTransaction() to roll everything back on error.
Step 5
Handle transient errors
Retry on TransientTransactionError or UnknownTransactionCommitResult, or use the driver's withTransaction() helper.
Step 6
End the session
Always call session.endSession() to release server resources.
What Interviewer Expects
- Knowledge that single-document writes are already atomic
- Understanding of ACID guarantees across multiple documents
- Awareness that replica set or sharded cluster is required
- The session-based start/commit/abort workflow
- Recognition of performance cost and retry handling
Common Mistakes
- Using transactions where a single-document atomic update would suffice
- Forgetting to pass the session into each operation
- Not handling transient transaction errors with retries
- Assuming transactions work on a standalone (non-replica-set) server
- Holding transactions open too long and causing lock contention
Best Answer (HR Friendly)
“A MongoDB transaction bundles several database changes so they all succeed together or all get undone, with none left half-done. You reach for one when a single action must update several records at once, like transferring money between two accounts, so the data can never end up inconsistent.”
Code Example
const session = client.startSession();
try {
await session.withTransaction(async () => {
const accounts = client.db('bank').collection('accounts');
await accounts.updateOne(
{ _id: 'alice' },
{ $inc: { balance: -100 } },
{ session }
);
await accounts.updateOne(
{ _id: 'bob' },
{ $inc: { balance: 100 } },
{ session }
);
});
} finally {
await session.endSession();
}Follow-up Questions
- Why are transactions unnecessary for single-document updates in MongoDB?
- What is a TransientTransactionError and how do you handle it?
- How do read concern and write concern affect a transaction?
- What are the performance costs of long-running transactions?
- How do transactions behave differently on a sharded cluster?
MCQ Practice
1. What deployment is required to use multi-document transactions?
Multi-document transactions require the oplog, so they need a replica set or a sharded cluster, not a standalone mongod.
2. Why are transactions often unnecessary in MongoDB?
Any update to a single document is atomic by default, so transactions are only needed when several documents must change together.
3. What must you pass to every operation inside a transaction?
Each read and write must receive the session so it is enrolled in the transaction; otherwise it runs outside it.
Flash Cards
When do you need a MongoDB transaction? — When a single logical operation must keep multiple documents or collections consistent at once.
What deployment do transactions require? — A replica set or a sharded cluster.
What does session.withTransaction() add over manual start/commit? — Automatic retry of transient errors and commit-unknown results.
Are single-document writes atomic without a transaction? — Yes, single-document updates are always atomic in MongoDB.