0
0
MongoDBquery~5 mins

Multi-document transactions in MongoDB

Choose your learning style9 modes available
Introduction
Multi-document transactions let you change many pieces of data at once, and make sure all changes happen together or none at all. This keeps your data safe and correct.
When you need to update several documents and want all updates to succeed or fail as one group.
When transferring money between two accounts and both accounts must update together.
When creating an order and reducing stock quantity at the same time.
When deleting related data from multiple collections and want to avoid partial deletions.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  // your operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
You must start a session before starting a transaction.
Always commit or abort the transaction to finish it properly.
Examples
This example inserts a document in one collection and updates another, all inside a transaction.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await collection1.insertOne({name: 'Alice'}, {session});
  await collection2.updateOne({name: 'Bob'}, {$inc: {score: 10}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
This example transfers money between two users, ensuring both updates happen together.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await accounts.updateOne({user: 'John'}, {$inc: {balance: -100}}, {session});
  await accounts.updateOne({user: 'Jane'}, {$inc: {balance: 100}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Sample Program
This program creates two accounts, then transfers 200 from Alice to Bob inside a transaction. It prints the final balances.
MongoDB
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('bank');
  const accounts = db.collection('accounts');

  // Prepare accounts
  await accounts.deleteMany({});
  await accounts.insertMany([
    { user: 'Alice', balance: 500 },
    { user: 'Bob', balance: 300 }
  ]);

  const session = client.startSession();

  try {
    session.startTransaction();

    // Alice sends 200 to Bob
    await accounts.updateOne({ user: 'Alice' }, { $inc: { balance: -200 } }, { session });
    await accounts.updateOne({ user: 'Bob' }, { $inc: { balance: 200 } }, { session });

    await session.commitTransaction();
  } catch (e) {
    await session.abortTransaction();
  } finally {
    session.endSession();
  }

  const results = await accounts.find().toArray();
  console.log(results);
  await client.close();
}

run();
OutputSuccess
Important Notes
Transactions work only on replica sets or sharded clusters, not standalone servers.
Always pass the session object to your operations inside the transaction.
Keep transactions short to avoid locking resources for too long.
Summary
Multi-document transactions let you group multiple changes so they all succeed or fail together.
You start a session, begin a transaction, do your operations, then commit or abort.
Use transactions to keep your data consistent when changing many documents.