Transactions and ACID Compliance
While MongoDB's document model minimizes the need for multi-document transactions, some operations still require atomicity across multiple documents or collections. MongoDB supports full multi-document ACID transactions since version 4.0.
1. ACID Properties Recap
| Property | Meaning |
|---|---|
| Atomicity | All operations succeed, or none do |
| Consistency | Data moves from one valid state to another |
| Isolation | Concurrent transactions don't interfere with each other |
| Durability | Committed changes survive system failures |
2. Single-Document Atomicity (Always On)
Every write to a single document is always atomic in MongoDB by default — even when updating deeply nested fields or arrays.
3. Multi-Document Transactions
const session = db.getMongo().startSession();
session.startTransaction();
try {
const accounts = session.getDatabase("bankDB").accounts;
accounts.updateOne(
{ accountId: "A100" },
{ $inc: { balance: -500 } },
{ session }
);
accounts.updateOne(
{ accountId: "B200" },
{ $inc: { balance: 500 } },
{ session }
);
session.commitTransaction();
} catch (error) {
session.abortTransaction();
throw error;
} finally {
session.endSession();
}
Requirement: Multi-document transactions require a replica set or sharded cluster — they are not available on a standalone MongoDB instance.
4. When to Use Transactions
- Bank transfers or financial ledger updates across accounts
- Inventory deduction that must stay in sync with order creation
- Any operation spanning multiple collections that must all succeed or all fail
5. When to Avoid Transactions
Transactions carry performance overhead. Whenever possible, model your schema (via embedding) so related data updates within a single document — avoiding the need for a transaction altogether.
Pro Tip: Reach for multi-document transactions as a safety net for cross-collection consistency — not as a substitute for good schema design.
6. Transactions Checklist
- ✅ Understand ACID properties in MongoDB's context
- ✅ Know single-document writes are always atomic
- ✅ Use startSession()/startTransaction()/commitTransaction() correctly
- ✅ Handle abortTransaction() on errors
- ✅ Recognize when embedding avoids the need for transactions
Key Takeaway: MongoDB gives you full ACID guarantees when you need them, but the best-performing applications lean on smart schema design to need multi-document transactions as rarely as possible.
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.