Problem Statement
What is required to use multi-document transactions in MongoDB?
Explanation
Multi-document ACID transactions were introduced in MongoDB 4.0 for replica sets and extended to sharded clusters in MongoDB 4.2. Transactions are not supported on standalone instances because they rely on the oplog for atomicity and rollback.
Transactions allow you to execute multiple read and write operations across multiple documents and collections atomically. Either all operations succeed and are committed, or all fail and are rolled back, ensuring data consistency and integrity.
Code Solution
SolutionRead Only
// Start a transaction
const session = client.startSession()
session.startTransaction()
try {
// Multiple operations in transaction
await db.accounts.updateOne(
{ _id: 1 },
{ $inc: { balance: -100 } },
{ session }
)
await db.accounts.updateOne(
{ _id: 2 },
{ $inc: { balance: 100 } },
{ session }
)
// Commit transaction
await session.commitTransaction()
} catch (error) {
// Rollback on error
await session.abortTransaction()
} finally {
session.endSession()
}