Transactions in MongoDB

 

💸 Transactions in MongoDB   

MongoDB is widely known for its flexibility and scalability as a NoSQL database. But did you know that it also supports multi-document ACID transactions — just like traditional relational databases? In this blog post, we’ll explore what transactions are, how they work in MongoDB, and how to use them effectively with MongoDB Compass, the official GUI for MongoDB.

📌 What are Transactions?

A transaction is a group of operations that are treated as a single unit of work. Either all the operations in a transaction succeed, or none of them do. This ensures data consistency and integrity, particularly in applications such as finance, inventory management, and user management.

In MongoDB, transactions are supported on replica sets (since version 4.0) and on sharded clusters (since version 4.2).

⚙️ Key Features of Transactions in MongoDB

  • Atomicity: All operations in a transaction are completed successfully or none at all.

  • Consistency: The database transitions from one valid state to another.

  • Isolation: Transactions do not interfere with each other.

  • Durability: Once a transaction is committed, the changes are permanent and cannot be reversed.

🔧 Setting Up MongoDB Compass for Transactions

MongoDB Compass doesn’t provide a dedicated "Transactions" tab like some SQL GUIs, but you can work with transactions using MongoDB shell inside Compass (mongosh) or through your application code.

✅ Requirements:

  • MongoDB version 4.0+

  • A replica set (Transactions don’t work on standalone instances)

  • MongoDB Compass is installed with Mongosh enabled

✍️ Using Transactions via MongoDB shell

To perform transactions using MongoDB shell:

Step 1:  Use or Create the Database

use bank

Step 2: Insert Sample Data

db.accounts.insertMany([ { _id: "alice", balance: 1000 }, { _id: "bob", balance: 500 } ])

Step 3: Perform a Transaction


const session = db.getMongo().startSession(); // Start session const bankDB = session.getDatabase("bank"); // Use the same DB in session const accounts = bankDB.accounts; try { session.startTransaction(); // Step 1: Deduct ₹500 from Alice accounts.updateOne( { _id: "alice" }, { $inc: { balance: -500 } } ); // Step 2: Add ₹500 to Bob accounts.updateOne( { _id: "bob" }, { $inc: { balance: 500 } } ); // Commit session.commitTransaction(); print("✅ Transaction committed."); } catch (e) { print("❌ Transaction aborted: " + e); session.abortTransaction(); } finally { session.endSession(); }

Step 4: Check Final Balances

db.accounts.find().pretty()

🧪 When Should You Use Transactions?

Use transactions when your application logic requires multiple related operations that must either all succeed or fail together. Common scenarios include:

  • Transferring funds between bank accounts

  • Placing an order and updating stock levels

  • Updating multiple documents across collections atomically

🧠 Final Thoughts

While MongoDB is known for its flexible document model, its support for ACID-compliant transactions makes it even more powerful. Using MongoDB Compass and its Mongosh integration, you can easily experiment with transactions and gain hands-on experience.

Whether you're building financial apps or any other system where data integrity matters, MongoDB transactions are a feature you don’t want to overlook.


 




Comments

Post a Comment

Popular posts from this blog

Query Operator's

Creating Documents in MongoDB(Insert)