Multi-Document Transactions in MongoDB

A
Author
27 Jun, 2026 1 min read 700 views

Single-document updates in MongoDB have always been atomic. Since version 4.0 (replica sets) and 4.2 (sharded clusters), MongoDB also supports multi-document ACID transactions.

Do you need one?

Often a good document design avoids the need. Updating an order and its embedded items is a single atomic operation. Use transactions when changes span documents or collections that must stay consistent, like moving money between two accounts.

Using withTransaction

const session = client.startSession();
try {
  await session.withTransaction(async () => {
    const accounts = client.db('bank').collection('accounts');

    const from = await accounts.findOneAndUpdate(
      { _id: fromId, balance: { $gte: amount } },
      { $inc: { balance: -amount } },
      { session, returnDocument: 'after' }
    );
    if (!from) throw new Error('Insufficient funds');

    await accounts.updateOne({ _id: toId }, { $inc: { balance: amount } }, { session });

    await client.db('bank').collection('ledger').insertOne(
      { fromId, toId, amount, at: new Date() },
      { session }
    );
  });
} finally {
  await session.endSession();
}

Pass the session to every operation inside the transaction. withTransaction commits at the end, aborts if your function throws, and automatically retries on transient errors such as write conflicts.

With Mongoose

await mongoose.connection.transaction(async (session) => {
  await Account.updateOne({ _id: fromId }, { $inc: { balance: -amount } }, { session });
  await Account.updateOne({ _id: toId }, { $inc: { balance: amount } }, { session });
});

Limits and good practice

  • Transactions require a replica set or sharded cluster (a single-node replica set works for local development).
  • By default a transaction must finish within 60 seconds; keep them short.
  • No slow external calls inside a transaction.
  • They have a performance cost; don't wrap every write in one out of habit.
  • Write concern majority makes committed data durable across a failover.
Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.