✅ MongoDB Transactions - Concept Overview
What is a Transaction?
A transaction in MongoDB is a group of operations (such as insert, update, delete, or read) executed together as a single unit of work. It guarantees atomicity — meaning either all operations succeed, or none of them do. This ensures data consistency across multiple documents and collections.
⚛️ Atomicity - Define
Atomicity means that a series of database operations are treated as a single unit:
Either all operations are completed successfully, or none are applied.
In the context of MongoDB:
- If one operation in a transaction fails, the entire transaction is rolled back.
- This protects your data from partial updates or inconsistent states, especially when working with multiple documents or collections.
🔄 Key Features of MongoDB Transactions
- Support for multi-document transactions (across multiple collections and databases).
- Can perform inserts, updates, deletes, and reads within a transaction.
- Supports aggregation operations (e.g.,
$count
,$group
) inside transactions. - Supports distributed transactions across sharded clusters (MongoDB 4.2+).
- Can create collections or indexes in a transaction under specific conditions.
💡 How Transactions Work
You start a transaction using a session.
Use the callback API or Core API to:
- Start a transaction.
- Execute your operations.
- Commit or abort the transaction.
If an error (like a duplicate key) occurs, you must abort the transaction (
session.abortTransaction()
).The driver may automatically retry transactions if errors like
TransientTransactionError
orUnknownTransactionCommitResult
occur.
⚠️ Important Considerations
✅ Allowed Operations
- Insert/update/delete across multiple collections and databases.
-
Create collections via:
- First insert,
- Upsert operation,
-
db.createCollection()
with readConcern set to "local".
-
Create indexes on:
- New empty collections in the same transaction.
🚫 Restrictions in Transactions
- ❌ No operations on
admin
,local
,config
, orsystem.*
collections. - ❌ No writes to capped collections.
- ❌ Cannot use
$graphLookup
on sharded collections. - ❌ Cannot use
distinct()
in sharded collections; use$group + $addToSet
. - ❌ No parallel/multi-threaded operations.
- ❌ No user management commands (
createUser
,listCollections
, etc.). - ❌ Cursors created outside the transaction cannot be used inside it.
⚙️ Write/Read Concerns and Preferences
- Set write concern, read concern, and read preference at the transaction level, not per operation.
- Avoid setting write concern for individual operations inside a transaction — it causes errors.
🛠️ Production Considerations
- Transactions are not supported on standalone deployments.
- You must deploy MongoDB as a replica set or a sharded cluster.
- Distributed transactions work across shards and require careful planning for performance and consistency.
- For sharded clusters, avoid creating collections inside transactions unless absolutely necessary.
📌 Summary
- MongoDB supports ACID-compliant transactions on replica sets and sharded clusters.
- Use them when you need reliable, consistent changes across multiple documents or collections.
- Always test transaction behavior carefully in production environments.
- ⚠️ Best Practice: Always wrap your transaction logic in retry logic for transient errors like
TransientTransactionError
orUnknownTransactionCommitResult
.
💻 Simple Transaction Example (Node.js)
const session = await mongoose.startSession();
try {
session.startTransaction();
await Order.create([{ userId: '123', amount: 500 }], { session });
await Inventory.updateOne({ item: 'book' }, { $inc: { stock: -1 } }, { session });
await session.commitTransaction();
console.log('Transaction committed.');
} catch (error) {
await session.abortTransaction();
console.error('Transaction aborted due to error:', error);
} finally {
session.endSession();
}
Top comments (0)