CHAPTER 19
Beginner
Transactions in MongoDB
Updated: May 16, 2026
15 min read
# CHAPTER 19
Transactions in MongoDB
1. Introduction
Historically, the biggest criticism of NoSQL databases was that they lacked "Transactions." If John sent $500 to Sarah, the database ran two separate queries: deduct from John, add to Sarah. If the server crashed after query 1, John's money vanished forever. In 2018 (Version 4.0), MongoDB changed the world by introducing Multi-Document ACID Transactions. In this chapter, we will learn how to wrap multiple NoSQL operations into unbreakable, all-or-nothing workflows, guaranteeing absolute financial-grade reliability.2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the four pillars of ACID compliance.
- Understand why Transactions require a Replica Set.
- Start a MongoDB Session.
-
Execute a Transaction using
startTransactionandcommitTransaction.
-
Abort and undo a Transaction using
abortTransaction.
3. What is ACID Compliance?
ACID is an acronym representing the gold standard of database reliability:- A (Atomicity): "All or nothing." If a transaction has 5 queries, and query 5 fails, queries 1-4 are instantly undone.
- C (Consistency): Data must always meet all Constraints (like our JSON Schema validators from Chapter 18).
- I (Isolation): If 1,000 users are transferring money at the exact same millisecond, their transactions operate in isolation and do not overlap.
- D (Durability): Once MongoDB replies "Success" (Committed), the data is permanently saved. Even if the power plug is pulled 0.1 seconds later, the data survives.
4. The Architectural Requirement: Replica Sets
CRITICAL NOTE: You *cannot* run Transactions on a standalone, local installation of MongoDB. Transactions fundamentally rely on the Oplog (Operations Log), which is only active when MongoDB is deployed as a Replica Set (A cluster of 1 Primary and 2 Secondary servers). *(If you are using MongoDB Atlas in the cloud, it is automatically a Replica Set, and Transactions will work perfectly!)*5. The Concept of "Sessions"
To track a transaction across multiple collections, you must initiate a Session. Every query you run inside the transaction must explicitly be told to run *inside* that Session.6. Executing a Transaction (The Workflow)
Let's simulate John transferring $500 to Sarah using themongosh terminal.
javascript
7. How Node.js Handles Transactions
In a real application, you will execute this in backend code. The official MongoDB Node.js driver provides a brilliant helper function calledwithTransaction() that automatically handles the commit and abort logic for you!
Node.js
8. Mini Project: E-Commerce Checkout
An E-commerce checkout requires extreme safety.
javascript
9. Common Mistakes
-
Forgetting the
{ session: session }parameter: If you open a transaction, but execute anupdateOne()and forget to pass the session object at the end, that query runs *outside* the transaction. If the transaction aborts, that query will NOT be undone!
- Overusing Transactions: Transactions are slow. They lock documents and require massive coordination across the cluster. In MongoDB, because you can embed an Order and its Items inside a *single document*, updating that single document is automatically atomic! You only need Transactions when updating *multiple different documents* across different collections.
10. Best Practices
- Keep them short: A transaction should execute in a few milliseconds. Never open a transaction, wait for a user to click a button on a webpage, and then commit it. It will hold server locks and destroy your database's performance.
11. Exercises
- 1. What does the "A" in ACID stand for, and what does it mean?
-
2.
Why will a
startTransaction()command throw an error if you are running a standard localmongodinstallation on your laptop?
12. MongoDB Challenges
What specific method is called to permanently save the changes made inside an open transaction session to the physical hard drive? *(Answer:session.commitTransaction())*
13. MCQ Quiz with Answers
Question 1
In the context of ACID properties, what does "Atomicity" guarantee in a Multi-Document MongoDB Transaction?
Question 2
When executing an updateOne() command that is intended to be part of an ongoing Transaction, what MUST be passed as an options argument to the query?
14. Interview Questions
- Q: Prior to version 4.0, MongoDB did not support Multi-Document Transactions. Explain the architectural reason why (Hint: The Document Model / Embedding), and why Transactions were eventually introduced anyway.
-
Q: Explain the workflow of a Transaction block, specifically detailing the roles of
startSession(),commitTransaction(), andabortTransaction().
15. FAQs
Q: Can a Transaction span across multiple Databases? A: Yes! A multi-document transaction can update a document inbillingdb and a document in usersdb simultaneously within the exact same session!
16. Summary
Transactions are your ultimate safety net. By utilizing Sessions and wrapping critical multi-document workflows insidecommit and abort blocks, you guarantee that API failures, server crashes, and runtime code errors will never result in corrupted, half-finished data states.