Open In App

Multi-Document Transaction in MongoDB

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a NoSQL database known for its flexible schema and high performance. While traditional relational databases offer ACID (Atomicity, Consistency, Isolation, Durability) transactions across multiple tables, NoSQL databases like MongoDB initially lacked this feature.

However, since MongoDB 4.0, multi-document transactions have been introduced, allowing users to execute multiple operations as a single atomic unit. In this article, we will understand a comprehensive guide to multi-document transactions in MongoDB by covering their usage, implementation, limitations and best practices in detail.

What are Multi-Document Transactions?

Multi-document transactions in MongoDB allow multiple write operations on multiple documents across one or more collections to be executed as an atomic unit. If any operation within a transaction fails, all operations are rolled back, ensuring data integrity.

When to Use Multi-Document Transactions

Multi-document transactions should be used when:

  • Ensuring consistency across multiple documents is required.
  • Implementing financial transactions (e.g., transferring money between accounts).
  • Updating related data across multiple collections.
  • Avoiding partial updates in multi-step processes.

Prerequisites for Using Transactions

Before using transactions, ensure that:

  • You are using MongoDB 4.0+ for single replica set transactions or MongoDB 4.2+ for sharded cluster transactions.
  • Your MongoDB deployment supports transactions (e.g., replica sets or sharded clusters with replica set shards).
  • The operations involved in the transaction comply with transaction limitations.

How to Implement Multi-Document Transactions

1. Starting a Session: Transactions in MongoDB require a session. You need to start a session before initiating a transaction.

2. Executing a Transaction: Transactions follow the startTransaction, commitTransaction and abortTransaction workflow.

Example: Using Multi-Document Transactions in Node.js

const { MongoClient } = require("mongodb");

async function runTransaction() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

try {
await client.connect();
const session = client.startSession();

session.startTransaction();
const db = client.db("banking");
const accounts = db.collection("accounts");

try {
await accounts.updateOne(
{ _id: 1 },
{ $inc: { balance: -500 } },
{ session }
);

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

await session.commitTransaction();
console.log("Transaction committed successfully");
} catch (error) {
await session.abortTransaction();
console.error("Transaction aborted: ", error);
} finally {
session.endSession();
}
} finally {
await client.close();
}
}

runTransaction();

Explanation:

The above query demonstrates a multi-document transaction in MongoDB using Node.js. The function runTransaction starts by connecting to the MongoDB server and initiating a session. Within this session, a transaction is started. Two updateOne operations are executed: one deducts $500 from the account with _id: 1, and the other adds $500 to the account with _id: 2.

Both operations are part of a single atomic transaction. If both operations succeed, commitTransaction finalizes the changes. However, if an error occurs during execution, abortTransaction is called, ensuring that no partial updates occur. This ensures data integrity in financial transactions.

Limitations of Multi-Document Transactions

Despite their usefulness, multi-document transactions in MongoDB have some limitations:

  • Performance Overhead: Transactions can impact performance due to increased resource usage.
  • Limited Duration: Transactions should be completed within 60 seconds.
  • Write Conflicts: Concurrent writes to the same document may cause conflicts.
  • Storage Engine Constraints: Only available in replica sets and sharded clusters.

Best Practices for Using Transactions

  • Minimize Transaction Scope: Keep transactions short to reduce locking and improve performance.
  • Use Bulk Operations When Possible: Bulk writes can sometimes replace transactions for efficiency.
  • Monitor and Handle Errors: Ensure proper error handling to avoid unintended rollbacks.
  • Use Transactions Only When Necessary: Since MongoDB supports atomic operations on single documents, use transactions only when multiple documents must be updated atomically.

Conclusion

Multi-document transactions in MongoDB provide ACID compliance, making it possible to handle complex business logic while ensuring data integrity. While they are powerful, they should be used judiciously due to performance implications. By understanding their implementation, limitations, and best practices, developers can leverage transactions effectively to enhance MongoDB applications.


Next Article
Article Tags :

Similar Reads