Master MongoDB ACID transactions for multi-document operations. Learn session management, transaction mechanics, error handling, and production patterns. Guarantee data consistency across multiple operations.
Guarantee consistency with ACID transactions across multiple operations.
const session = client.startSession()
try {
await session.withTransaction(async () => {
// All operations here are atomic
await users.insertOne({ name: 'John' }, { session })
await accounts.insertOne({ userId: 'xxx', balance: 100 }, { session })
// If any fails, ALL roll back
})
} catch (error) {
console.error('Transaction failed:', error)
} finally {
await session.endSession()
}
async function transferMoney(fromId, toId, amount) {
const session = client.startSession()
try {
await session.withTransaction(async () => {
// Deduct from account A
await accounts.updateOne(
{ _id: fromId },
{ $inc: { balance: -amount } },
{ session }
)
// Add to account B
await accounts.updateOne(
{ _id: toId },
{ $inc: { balance: amount } },
{ session }
)
// Both succeed, or both rollback - NO PARTIAL TRANSFERS!
})
} catch (error) {
// Transaction failed, money not transferred
console.error('Transfer failed:', error)
} finally {
await session.endSession()
}
}
const session = client.startSession()
// Configure session
const session = client.startSession({
defaultTransactionOptions: {
readConcern: { level: 'snapshot' },
w...