Multi-Document ACID Transactions

Multi-Document ACID Transactions in NoSQL Databases: Traditionally, NoSQL databases only guaranteed atomicity for single-document writes.

Traditionally, NoSQL databases only guaranteed atomicity for single-document writes. Starting in MongoDB 4.0+, developers can execute multi-document ACID transactions across collections.


1. When to Use Transactions

Use transactions only when two or more documents MUST update atomically, such that if any operation fails, all previous writes are rolled back:

  • Transferring account balances between two users.
  • Deducting warehouse inventory while generating an order receipt.
  • Updating user profiles and incrementing global organization seat counters.

2. Implementing a Transaction in Node.js

const { MongoClient } = require("mongodb");
const client = new MongoClient(process.env.MONGODB_URI);

async function transferFunds(senderId, receiverId, transferAmount) {
  const session = client.startSession();

  try {
    session.startTransaction({
      readConcern: { level: "snapshot" },
      writeConcern: { w: "majority" }
    });

    const walletsCollection = client.db("banking").collection("wallets");

    // 1. Debit sender account (ensure balance is sufficient)
    const debitResult = await walletsCollection.updateOne(
      { user_id: senderId, balance: { $gte: transferAmount } },
      { $inc: { balance: -transferAmount } },
      { session }
    );

    if (debitResult.matchedCount === 0) {
      throw new Error("Transaction aborted: Insufficient funds or sender not found.");
    }

    // 2. Credit receiver account
    await walletsCollection.updateOne(
      { user_id: receiverId },
      { $inc: { balance: transferAmount } },
      { session }
    );

    // 3. Commit transaction permanently
    await session.commitTransaction();
    console.log("Funds transferred successfully!");
  } catch (error) {
    // If any step fails, roll back all mutations
    await session.abortTransaction();
    console.error("Transfer failed, state reverted:", error.message);
    throw error;
  } finally {
    await session.endSession();
  }
}