0
0
MongoDBquery~3 mins

Why transactions are needed in MongoDB - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your important data changes halfway and leaves your system broken? Transactions are the safety net you need.

The Scenario

Imagine you are updating a bank account balance and the transaction history manually by editing multiple documents one by one in MongoDB.

If something goes wrong halfway, like a power cut or a mistake, your data will be inconsistent.

The Problem

Manually updating multiple related documents is slow and risky.

You might forget to update one part or end up with partial changes, causing errors and confusion.

The Solution

Transactions let you group multiple operations into one unit.

Either all changes happen together, or none happen at all, keeping your data safe and consistent.

Before vs After
Before
db.accounts.updateOne({id:1}, {$inc: {balance: -100}})
db.transactions.insertOne({accountId:1, amount:-100})
After
const session = client.startSession();
session.withTransaction(() => {
  db.accounts.updateOne({id:1}, {$inc: {balance: -100}}, {session});
  db.transactions.insertOne({accountId:1, amount:-100}, {session});
});
session.endSession();
What It Enables

Transactions enable safe, reliable updates across multiple documents, ensuring your data stays correct even if something unexpected happens.

Real Life Example

When transferring money between two bank accounts, transactions ensure that the amount is deducted from one account and added to the other together, preventing money loss or duplication.

Key Takeaways

Manual updates across documents can cause inconsistent data.

Transactions group operations to succeed or fail as one.

This keeps your database accurate and trustworthy.