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();
}
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.
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
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.