0
0
MongoDBquery~3 mins

Why Session and transaction syntax in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one small mistake could undo all your hard work automatically?

The Scenario

Imagine you are updating multiple related records in a database by hand, one by one. If something goes wrong halfway, you have to remember which changes were made and fix them manually. This is like trying to balance your checkbook by writing down every transaction on paper without any automatic help.

The Problem

Doing updates manually is slow and risky. You might forget to update some records or accidentally leave the database in a broken state. Fixing these mistakes takes a lot of time and can cause data loss or confusion.

The Solution

Sessions and transactions let you group many database operations together so they all succeed or fail as one. If any step fails, everything rolls back automatically. This keeps your data safe and consistent without extra effort.

Before vs After
Before
db.collection.updateOne({id:1}, {$set: {status: 'pending'}})
db.collection.updateOne({id:2}, {$set: {status: 'pending'}})
After
const session = client.startSession();
session.withTransaction(async () => {
  await db.collection.updateOne({id:1}, {$set: {status: 'pending'}}, {session});
  await db.collection.updateOne({id:2}, {$set: {status: 'pending'}}, {session});
});
What It Enables

It enables you to make complex changes safely and reliably, just like a safety net that catches mistakes before they cause harm.

Real Life Example

When booking a flight and a hotel together, transactions ensure either both bookings succeed or neither does, so you never pay for one without the other.

Key Takeaways

Manual updates can cause errors and data inconsistency.

Sessions and transactions group operations to succeed or fail together.

This keeps your database safe and your data trustworthy.