SyntaxStudy
Sign Up
MongoDB Transactions and Multi-Document Atomicity
MongoDB Beginner 1 min read

Transactions and Multi-Document Atomicity

MongoDB guarantees atomicity for single-document operations, including updates to embedded arrays. For operations that must span multiple documents or multiple collections atomically, MongoDB supports multi-document ACID transactions starting from version 4.0. Transactions in MongoDB behave like transactions in relational databases: all operations within the session either all commit or all roll back. Transactions require a replica set or sharded cluster — they cannot run on a standalone server. Because transactions hold locks and can hurt throughput, the best schema design avoids needing them. When you do need a transaction, keep it short and never perform network calls or user interaction inside an open transaction.
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()
}