MongoDB
Beginner
1 min read
Transactions and Multi-Document Atomicity
Example
// Multi-document transaction (Node.js driver)
const client = new MongoClient(uri)
await client.connect()
const session = client.startSession()
try {
await session.withTransaction(async () => {
const accounts = client.db('bank').collection('accounts')
// Debit sender
await accounts.updateOne(
{ _id: "account_A", balance: { $gte: 200 } },
{ $inc: { balance: -200 } },
{ session }
)
// Credit receiver
await accounts.updateOne(
{ _id: "account_B" },
{ $inc: { balance: 200 } },
{ session }
)
// If either operation throws, the whole transaction rolls back
})
console.log('Transfer complete')
} catch (err) {
console.error('Transaction aborted:', err)
} finally {
await session.endSession()
await client.close()
}