Skip to main content
MongoDB
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 startTransaction and commitTransaction.
  • 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 the mongosh terminal.
javascript
123456789101112131415161718192021222324252627282930313233343536
// 1. Start the Session
session = db.getMongo().startSession()

// 2. Open the Transaction Vault
session.startTransaction()

try {
    // 3. Execute the queries, strictly passing the {session} parameter!
    
    // Deduct $500 from John
    db.accounts.updateOne(
        { user: "John" }, 
        { $inc: { balance: -500 } }, 
        { session: session } // CRITICAL!
    )
    
    // Add $500 to Sarah
    db.accounts.updateOne(
        { user: "Sarah" }, 
        { $inc: { balance: 500 } }, 
        { session: session } // CRITICAL!
    )
    
    // 4. Everything succeeded! Save it permanently to the hard drive.
    session.commitTransaction()
    print("Transaction Successful!")
    
} catch (error) {
    // 5. If ANYTHING failed (e.g., John had insufficient funds causing a validation error)
    // We instantly UNDO the entire transaction!
    session.abortTransaction()
    print("Transaction Failed and Rolled Back!")
} finally {
    // 6. Always end the session to free up server RAM
    session.endSession()
}

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 called withTransaction() that automatically handles the commit and abort logic for you!
Node.js
123456789101112
const session = client.startSession();

try {
  await session.withTransaction(async () => {
    // Query 1
    await accounts.updateOne({ user: "John" }, { $inc: { balance: -500 } }, { session });
    // Query 2
    await accounts.updateOne({ user: "Sarah" }, { $inc: { balance: 500 } }, { session });
  });
} finally {
  await session.endSession();
}

8. Mini Project: E-Commerce Checkout

An E-commerce checkout requires extreme safety.
javascript
1234567
// INSIDE A TRANSACTION SESSION:
// 1. Check Inventory (Make sure Laptop > 0)
// 2. Deduct Inventory (Laptop - 1)
// 3. Process Payment (Charge Credit Card via Stripe API)
// 4. Create Order Document
// If the Stripe API fails in step 3, the transaction ABORTS, 
// and the Laptop inventory is magically restored to its original value!

9. Common Mistakes

  • Forgetting the { session: session } parameter: If you open a transaction, but execute an updateOne() 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. 1. What does the "A" in ACID stand for, and what does it mean?
  1. 2. Why will a startTransaction() command throw an error if you are running a standard local mongod installation 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(), and abortTransaction().

15. FAQs

Q: Can a Transaction span across multiple Databases? A: Yes! A multi-document transaction can update a document in billingdb 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 inside commit and abort blocks, you guarantee that API failures, server crashes, and runtime code errors will never result in corrupted, half-finished data states.

17. Next Chapter Recommendation

Up until now, you have been running everything locally. It is time to deploy to the internet. In Chapter 20: MongoDB Atlas and Cloud Databases, we will migrate our architecture to AWS/GCP using MongoDB's official managed cloud service.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·