MongoDB is widely known as a NoSQL database that provides flexibility and scalability. Traditionally, NoSQL databases traded transactional guarantees (ACID compliance) for speed and horizontal scaling. However, as MongoDB matured, it introduced multi-document transactions starting from version 4.0 (2018), making it possible to handle complex business use cases that require consistent operations.
In this guide, we’ll explore what transactions are, how they work in MongoDB, use cases, examples, and best practices.
A transaction is a sequence of database operations that are executed as a single unit of work. Either all operations succeed (commit) or none of them do (rollback).
Transactions follow the ACID properties:
startSession()), then a transaction is begun, committed, or aborted.MongoDB always guaranteed atomicity for single-document writes, even before transactions:
db.accounts.updateOne(
{ _id: 1 },
{ $inc: { balance: -100 } }
); This operation is atomic on its own.
Suppose we want to transfer money between two accounts. Both operations must succeed, or none should.
const session = db.getMongo().startSession();
session.startTransaction();
try {
const accountsCollection = session.getDatabase("bank").accounts;
// Deduct from sender
accountsCollection.updateOne(
{ _id: 1 },
{ $inc: { balance: -100 } },
{ session }
);
// Add to receiver
accountsCollection.updateOne(
{ _id: 2 },
{ $inc: { balance: 100 } },
{ session }
);
// Commit transaction
session.commitTransaction();
print("Transaction committed successfully.");
} catch (error) {
// Rollback on error
session.abortTransaction();
print("Transaction aborted due to error: " + error);
} finally {
session.endSession();
}
✅ If either operation fails, the entire transaction rolls back.
MongoDB transactions bridge the gap between NoSQL flexibility and SQL-like consistency. While MongoDB is still optimized for document-based atomic operations, the ability to perform multi-document ACID transactions makes it suitable for enterprise-grade applications in finance, eCommerce, and booking systems.
If you’re building apps where data integrity is mission-critical, transactions in MongoDB are your best friend.
Latest tech news and coding tips.
Visual Studio Code (VS Code) is powerful out of the box, but its real strength…
1. What Is a Variable in JavaScript? A variable is a named container used to store data…
1. What Is a Queue? A Queue is a linear data structure that follows the principle: FIFO – First…
Angular is a full-featured frontend framework built by Google for creating large, maintainable, and high-performance web applications.…
What Is Responsive Web Design? Responsive Web Design (RWD) is an approach to building websites…
The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with…