Transactions in MongoDBIntermediate
1Question 1 of 1
javascriptHow do Multi-Document ACID Transactions work in MongoDB?
Explanation & Concept
Starting in MongoDB 4.0, MongoDB supports multi-document ACID transactions across replica sets (and sharded clusters in 4.2).
Transactions use a two-phase commit protocol and snapshot isolation. If any operation within the session errors, `abortTransaction()` rolls back all writes across all affected collections and documents.
Code Example
javascript
const session = client.startSession();
session.startTransaction({
readConcern: { level: "snapshot" },
writeConcern: { level: "majority" }
});
try {
// Transfer funds between two users
await accounts.updateOne({ _id: fromId }, { $inc: { balance: -200 } }, { session });
await accounts.updateOne({ _id: toId }, { $inc: { balance: 200 } }, { session });
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}How It Works & Key Takeaways
Passing `{ session }` binds both update commands to the same atomic transaction. If either update fails, none of the changes persist.
Mock Test · 1 Questions · Optional
Ready for Embedded vs Referenced Data?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions