Paramclasses Academy - Blog

Tutorials Details

←
Post 23 of 35
→

MongoDB Transactions Explained: Maintain Data Consistency

MongoDB Transactions Explained: Maintain Data Consistency

November 5, 2026

MongoDB Transactions Explained: Maintain Data Consistency

1. Introduction to MongoDB Transactions

MongoDB transactions allow you to perform multiple database operations as one single unit of work.

A transaction ensures that either all operations are completed successfully or none of them are applied.

For example, imagine a banking application where Rahul transfers ₹5,000 to Priya.

Two operations are required:

  1. Deduct ₹5,000 from Rahul's account.

  2. Add ₹5,000 to Priya's account.

What happens if money is deducted from Rahul's account but the application fails before adding it to Priya's account?

This creates an inconsistent database.

MongoDB Transactions solve this problem by ensuring that both operations succeed together or are rolled back together.

2. What Are ACID Properties?

MongoDB transactions follow ACID properties.

ACID stands for:

Property Meaning
Atomicity All operations succeed together or none are applied.
Consistency Data remains valid before and after a transaction.
Isolation Concurrent transactions are isolated according to transaction isolation rules.
Durability Committed changes are persisted according to the configured write concern.

Understanding ACID with an Example

Suppose Rahul transfers ₹5,000 to Priya.

  • Atomicity: Both debit and credit operations must succeed together.

  • Consistency: Account balances must remain correct.

  • Isolation: Concurrent transactions must not expose partial transaction changes.

  • Durability: Once committed with suitable write concern, the changes are persisted.

3. How MongoDB Transactions Work

A MongoDB transaction generally follows these steps:

  1. Start a session.

  2. Start a transaction.

  3. Perform database operations.

  4. Commit the transaction if everything succeeds.

  5. Abort the transaction if an error occurs.

  6. End the session.

Important transaction methods:

Method Purpose
startSession() Creates a database session.
startTransaction() Starts a transaction in that session.
commitTransaction() Saves all transaction changes.
abortTransaction() Discards transaction changes.
endSession() Ends the session.

4. Create a Database for the Transaction Example

We will create a banking database named bankDB.

use bankDB

Create two accounts:

db.accounts.insertMany([
    {
        accountHolder: "Rahul",
        balance: 10000
    },
    {
        accountHolder: "Priya",
        balance: 5000
    }
])

Check the account records:

db.accounts.find()

Example output:

[
    {
        _id: ObjectId("..."),
        accountHolder: "Rahul",
        balance: 10000
    },
    {
        _id: ObjectId("..."),
        accountHolder: "Priya",
        balance: 5000
    }
]

For this example, assume these two account records already exist before starting the transaction.

5. Start a MongoDB Transaction

First, create a session using startSession().

const session = db.getMongo().startSession()

Now start the transaction:

session.startTransaction()

Access the database through the session:

const bankDB = session.getDatabase("bankDB")

All database operations performed through this session database will belong to the transaction.

6. Perform Multiple Operations Inside a Transaction

Let's transfer ₹5,000 from Rahul's account to Priya's account.

First, get the accounts collection:

const accounts = bankDB.getCollection("accounts")

Step 1: Deduct Money from Rahul's Account

const debitResult = accounts.updateOne(
    {
        accountHolder: "Rahul",
        balance: { $gte: 5000 }
    },
    {
        $inc: { balance: -5000 }
    }
)

The condition balance: { $gte: 5000 } ensures Rahul has enough balance.

Check whether the debit operation succeeded:

if (debitResult.matchedCount !== 1) {
    throw new Error("Insufficient balance or Rahul's account not found")
}

Step 2: Add Money to Priya's Account

const creditResult = accounts.updateOne(
    {
        accountHolder: "Priya"
    },
    {
        $inc: { balance: 5000 }
    }
)

Check whether Priya's account was found:

if (creditResult.matchedCount !== 1) {
    throw new Error("Priya's account not found")
}

Both operations are part of the same transaction.

7. Commit a MongoDB Transaction

If all operations succeed, use commitTransaction().

session.commitTransaction()

This commits the transaction and makes its changes visible outside the transaction.

End the session:

session.endSession()

After a successful transfer, the balances will be:

Account Holder Previous Balance New Balance
Rahul ₹10,000 ₹5,000
Priya ₹5,000 ₹10,000

8. What Is abortTransaction() in MongoDB?

Sometimes an operation inside a transaction fails.

For example:

  • Rahul has insufficient balance.

  • Priya's account does not exist.

  • An update operation encounters an error.

In such situations, use abortTransaction() to cancel the transaction.

session.abortTransaction()

This discards the changes made by the transaction.

For example, if Rahul's balance was deducted but the credit operation failed, aborting the transaction rolls back the debit as well.

End the session after aborting:

session.endSession()

9. Complete MongoDB Transaction Example

Here is the complete example using try, catch, and finally.

Run this after ensuring the two account records already exist and the server supports transactions.

const session = db.getMongo().startSession()

try {

    session.startTransaction()

    const bankDB = session.getDatabase("bankDB")

    const accounts = bankDB.getCollection("accounts")

    // Step 1: Deduct money from Rahul
    const debitResult = accounts.updateOne(
        {
            accountHolder: "Rahul",
            balance: { $gte: 5000 }
        },
        {
            $inc: { balance: -5000 }
        }
    )

    if (debitResult.matchedCount !== 1) {
        throw new Error("Insufficient balance or Rahul not found")
    }

    // Step 2: Add money to Priya
    const creditResult = accounts.updateOne(
        {
            accountHolder: "Priya"
        },
        {
            $inc: { balance: 5000 }
        }
    )

    if (creditResult.matchedCount !== 1) {
        throw new Error("Priya's account not found")
    }

    // Step 3: Commit transaction
    session.commitTransaction()

    print("Transaction completed successfully!")

} catch (error) {

    // Roll back transaction if an error occurs
    session.abortTransaction()

    print("Transaction failed: " + error.message)

} finally {

    // End session
    session.endSession()

}

Important: If a commit itself returns an uncertain result, production applications need to handle transaction commit retries according to MongoDB's transaction error-handling guidance. Do not assume every commit error means the transaction definitely rolled back.

10. Verify the Final Account Balances

After the transaction completes, check the accounts collection:

db.accounts.find(
    {},
    {
        _id: 0,
        accountHolder: 1,
        balance: 1
    }
)

Expected result after a successful transfer:

[
    {
        accountHolder: "Rahul",
        balance: 5000
    },
    {
        accountHolder: "Priya",
        balance: 10000
    }
]

If the transaction is aborted, the original balances remain unchanged.

11. MongoDB Transactions vs Normal Operations

Feature Normal Operations Transactions
Single document update Atomic Atomic
Multiple document operations Not one atomic unit Can be atomic together
Rollback multiple operations Not automatic as a group Supported using abort
Commit control No explicit transaction commit commitTransaction()
Use case Simple database updates Multi-document consistency

MongoDB already provides atomicity for individual document writes. Use multi-document transactions when multiple documents or collections must change together.

12. Where Are MongoDB Transactions Used?

MongoDB transactions are useful in applications such as:

  1. Banking applications – transferring money between accounts.

  2. E-commerce websites – updating inventory and creating orders.

  3. Payment systems – recording payments and updating account balances.

  4. Booking systems – reserving seats and creating booking records.

  5. Student management systems – updating related records together.

13. Important MongoDB Transaction Rules

  • Transactions require a replica set or a sharded cluster.

  • A standalone MongoDB deployment does not support multi-document transactions.

  • For local transaction practice, configure MongoDB as a single-node replica set.

  • Use session-associated database and collection operations inside the transaction.

  • Keep transactions short and avoid unnecessary operations.

  • Create the collections and indexes needed by the transaction before starting it.

  • Transactions can have additional performance costs, so good schema design is still important.

14. Practical Exercise

Try the following tasks:

  1. Create a database named bankDB.

  2. Create an accounts collection.

  3. Insert two account records.

  4. Start a session and transaction.

  5. Deduct ₹2,000 from one account.

  6. Add ₹2,000 to another account.

  7. Commit the transaction.

  8. Repeat the example but intentionally cause an error.

  9. Use abortTransaction() and verify that the original balances remain unchanged.

15. Frequently Asked Questions (FAQs)

Q1. What is a transaction in MongoDB?

A transaction is a group of database operations that succeed together or are rolled back together.

Q2. What is ACID in MongoDB?

ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties help maintain reliable database operations.

Q3. What does commitTransaction() do?

It commits all changes made within the transaction.

Q4. What does abortTransaction() do?

It cancels the transaction and discards its uncommitted changes.

Q5. Does MongoDB support multi-document transactions?

Yes. MongoDB supports multi-document transactions on replica sets and sharded clusters.

Q6. Can we use transactions on a standalone MongoDB server?

No. Multi-document transactions require a replica set or sharded cluster. A local standalone server can be configured as a single-node replica set for learning and testing.

Q7. Are transactions required for every MongoDB update?

No. A single-document write is already atomic. Transactions are useful when multiple document changes must succeed or fail together.

16. Conclusion

MongoDB Transactions help developers maintain data consistency when an application performs multiple related database operations.

In this tutorial, we learned how to:

  • Understand ACID properties.

  • Create a MongoDB session.

  • Start a transaction using startTransaction().

  • Perform multiple database operations.

  • Save changes using commitTransaction().

  • Roll back changes using abortTransaction().

  • Verify transaction results.

By understanding MongoDB transactions, you can build more reliable applications for banking, e-commerce, payment processing, and other systems where data consistency is important.

←
Post 23 of 35
→