Multi-Document Transaction in MongoDB
Last Updated :
20 Feb, 2025
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.
Similar Reads
Transactions in MongoDB
MongoDB is a popular NoSQL database known for its scalability and flexibility, but handling multiple operations across multiple documents and collections has always been a challenge for developers. With the introduction of multi-document ACID transactions in MongoDB 4.0, developers can now ensure da
8 min read
MongoDB ACID Transactions
MongoDB ACID transactions are fundamental for ensuring data integrity in database transactions. In MongoDB, ACID properties play a crucial role in maintaining the reliability and consistency of data operations. In this article, We will learn about ACID transactions in MongoDB, understand their impor
9 min read
Using Transactions in MongoDB
MongoDB is originally designed as a NoSQL database which has evolved significantly to support more complex operations, including transactions. Since version 4.0, MongoDB supports multi-document transactions and allows developers to perform operations across multiple documents and even multiple colle
7 min read
MongoDB - Insert Multiple Document Using MongoShell
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed
2 min read
How to Use MongoDB Transactions in Node.js?
Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js. PrerequisitesMongoDB (Version 4.0 or higher Recommended
2 min read
Transactions in Mongoose
Mongoose Transactions allows to execute multiple database operations within a single transaction, ensuring that they are either all successful or none of them are. Mongoose provides powerful tools to manage transactions effectively. Transactions in MongooseStep 1: First, make sure you have Mongoose
5 min read
MongoDB Queries Document
MongoDB is NoSQL(Not only SQL) database because the storage and retrieval of data in MongoDB are not in the form of tables like in SQL. It stores data in a BSON structure. It uses BSON or Binary JSON data format to organize and store data. This data format includes all JSON data types and adds types
15+ min read
Replica Set Deployment in MongoDB
MongoDB Replica Sets are essential for ensuring high availability, data redundancy and fault tolerance in modern database applications. By maintaining identical datasets across multiple nodes Replica Sets offer automatic failover, consistent data replication and the ability to scale horizontally. In
7 min read
How Document Versioning Works in MongoDB?
Document versioning in MongoDB is a powerful feature that allows developers to track changes to documents over time. It is particularly useful for applications that require auditing, historical analysis, or data integrity enforcement. In this article, We will learn about How document versioning work
4 min read
MongoDB - Insert Single Document Using MongoShell
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations and add new documents to the existing collection. You are allo
2 min read