6 min read
•Question 10 of 27hardHow do transactions work in MongoDB?
Understanding ACID transactions.
What You'll Learn
- When to use transactions
- Multi-document transactions
- Best practices
When to Use Transactions
- Transfer money between accounts
- Order processing with inventory update
- Any operation requiring atomicity across documents
Basic Transaction
code.jsJavaScript
const session = client.startSession();
try {
session.startTransaction();
// Deduct from sender
await accounts.updateOne(
{ _id: senderId },
{ $inc: { balance: -amount } },
{ session }
);
// Add to receiver
await accounts.updateOne(
{ _id: receiverId },
{ $inc: { balance: amount } },
{ session }
);
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}With Mongoose
code.jsJavaScript
const session = await mongoose.startSession();
await session.withTransaction(async () => {
await Order.create([{ userId, items, total }], { session });
await Product.updateMany(
{ _id: { $in: itemIds } },
{ $inc: { stock: -1 } },
{ session }
);
await User.updateOne(
{ _id: userId },
{ $inc: { orderCount: 1 } },
{ session }
);
});
session.endSession();Requirements
- MongoDB 4.0+ for replica sets
- MongoDB 4.2+ for sharded clusters
- WiredTiger storage engine
Best Practices
- Keep transactions short
- Limit operations per transaction
- Handle retries for transient errors
- Consider single-document atomicity first