MongoDB & NoSQL (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
How do Multi-Document ACID Transactions work in MongoDB?
senior LevelMost AskedCode ExampleState ManagementDatabases & SQL
In Simple Words: Supported on Replica Sets (v4.0+) and Sharded Clusters (v4.2+):
- Provides full snapshot isolation across multiple collections and documents:
typescript
const session = client.startSession();
session.startTransaction();
try {
await ordersCollection.insertOne({ orderId: 99, amount: 150 }, { session });
await accountsCollection.updateOne({ userId: 1 }, { $inc: { balance: -150 } }, { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
} finally {
await session.endSession();
}
- Cost: Uses two-phase commit protocol; incurs significant locking overhead. Design schemas to use single-document embedding for atomicity whenever possible.