![]() |
VOOZH | about |
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.
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.
Multi-document transactions should be used when:
Before using transactions, ensure that:
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.
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.
Despite their usefulness, multi-document transactions in MongoDB have some limitations:
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.