0
0
MongodbConceptBeginner · 3 min read

Multi Document Transaction in MongoDB: What It Is and How It Works

A multi document transaction in MongoDB is a way to group multiple operations on different documents or collections into a single, all-or-nothing action. This means either all changes succeed together or none are applied, ensuring data consistency across multiple documents.
⚙️

How It Works

Imagine you are paying for groceries and want to update your bank account balance and the store's sales record at the same time. You want both updates to happen together or not at all, so your money isn't lost if the store's record fails to update.

In MongoDB, a multi document transaction works like this: it groups several operations on different documents or collections into one package. MongoDB then makes sure all these operations complete successfully before saving any changes. If any operation fails, MongoDB rolls back all changes, leaving the data as it was before.

This mechanism helps keep your data accurate and consistent, especially when multiple documents must change together to reflect a real-world event.

💻

Example

This example shows how to use a multi document transaction in MongoDB with Node.js. It updates two different collections inside a transaction.

javascript
const { MongoClient } = require('mongodb');

async function runTransaction() {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const session = client.startSession();

    const users = client.db('shop').collection('users');
    const orders = client.db('shop').collection('orders');

    const transactionResults = await session.withTransaction(async () => {
      await users.updateOne(
        { _id: 1 },
        { $inc: { balance: -50 } },
        { session }
      );

      await orders.insertOne(
        { userId: 1, item: 'Book', price: 50 },
        { session }
      );
    });

    if (transactionResults) {
      console.log('Transaction committed successfully.');
    } else {
      console.log('Transaction aborted.');
    }
  } finally {
    await session.endSession();
    await client.close();
  }
}

runTransaction().catch(console.error);
Output
Transaction committed successfully.
🎯

When to Use

Use multi document transactions when you need to make sure multiple changes across different documents or collections happen together. This is important when partial updates could cause errors or inconsistent data.

For example, in banking apps, transferring money requires updating both the sender's and receiver's accounts. In e-commerce, placing an order might update inventory and create a purchase record. Transactions ensure these related updates are safe and reliable.

Key Points

  • Multi document transactions group multiple operations into one atomic action.
  • All operations succeed or all fail together, preserving data consistency.
  • Transactions can span multiple collections and documents.
  • They add some overhead, so use them only when necessary.
  • Supported in MongoDB 4.0 and later for replica sets, and 4.2+ for sharded clusters.

Key Takeaways

Multi document transactions ensure multiple changes happen together or not at all in MongoDB.
They help keep data consistent across different documents and collections.
Use transactions for critical operations like money transfers or order processing.
Transactions add overhead, so use them only when atomicity is required.
MongoDB supports multi document transactions starting from version 4.0.