0
0
MongoDBquery~5 mins

Why transactions are needed in MongoDB

Choose your learning style9 modes available
Introduction

Transactions help keep data safe and correct when many changes happen at once. They make sure all changes happen together or not at all.

When you need to update multiple documents and want all updates to succeed or fail together.
When you want to avoid partial changes that can cause wrong or broken data.
When working with money transfers between accounts to ensure both accounts update correctly.
When multiple users are changing data at the same time and you want to keep data consistent.
When you want to undo all changes if something goes wrong during a set of operations.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  // perform multiple operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Transactions in MongoDB use sessions to group operations.
You must commit the transaction to save changes or abort to cancel.
Examples
This example inserts a document and updates another inside a transaction to keep data consistent.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await collection1.insertOne({name: 'Alice'}, {session});
  await collection2.updateOne({user: 'Alice'}, {$inc: {balance: 100}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
This example replaces an item by deleting and inserting inside a transaction to avoid partial changes.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await collection.deleteOne({item: 'old'}, {session});
  await collection.insertOne({item: 'new'}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Sample Program

This program transfers 100 units from Alice's account to Bob's account using a transaction. If any update fails, no money is moved.

MongoDB
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('bank');
  const accounts = db.collection('accounts');

  const session = client.startSession();
  try {
    session.startTransaction();

    // Withdraw 100 from Alice
    await accounts.updateOne({name: 'Alice'}, {$inc: {balance: -100}}, {session});

    // Deposit 100 to Bob
    await accounts.updateOne({name: 'Bob'}, {$inc: {balance: 100}}, {session});

    await session.commitTransaction();
    console.log('Transaction committed successfully');
  } catch (error) {
    await session.abortTransaction();
    console.log('Transaction aborted due to error:', error.message);
  } finally {
    session.endSession();
    await client.close();
  }
}

run();
OutputSuccess
Important Notes

Transactions help keep data accurate when many changes happen together.

Without transactions, partial updates can cause wrong data.

Use transactions when you need all-or-nothing changes across multiple documents or collections.

Summary

Transactions group multiple operations to succeed or fail together.

They keep data safe and consistent in MongoDB.

Use transactions for complex updates or when data integrity matters.