0
0
MongoDBquery~5 mins

When transactions are necessary vs unnecessary in MongoDB

Choose your learning style9 modes available
Introduction

Transactions help keep data safe and correct when many changes happen together. Sometimes you need them, sometimes you don't.

When you need to update multiple documents and all must succeed or fail together, like transferring money between accounts.
When you want to make sure data stays consistent after several related changes.
When your operation involves multiple collections and you want to avoid partial updates.
When you want to prevent errors from leaving your database in a broken state.
When you need to rollback changes if something goes wrong during a set of operations.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  // your operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}

Use startTransaction() to begin a transaction.

Always commit or abort the transaction to finish it properly.

Examples
This example transfers 100 units from one account to another safely.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await collection1.updateOne({ _id: 1 }, { $inc: { balance: -100 } }, { session });
  await collection2.updateOne({ _id: 2 }, { $inc: { balance: 100 } }, { session });
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Simple updates on one document usually don't need transactions.
MongoDB
// No transaction needed for a single document update
await collection.updateOne({ _id: 1 }, { $set: { status: 'active' } });
Sample Program

This program safely transfers 50 units from account 1 to account 2 using a transaction.

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();

    await accounts.updateOne({ _id: 1 }, { $inc: { balance: -50 } }, { session });
    await accounts.updateOne({ _id: 2 }, { $inc: { balance: 50 } }, { session });

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

run();
OutputSuccess
Important Notes

Transactions add some overhead, so use them only when needed.

For single document changes, MongoDB ensures atomicity without transactions.

Always handle errors to abort transactions and avoid partial updates.

Summary

Use transactions when multiple related changes must all succeed or fail together.

Skip transactions for simple single-document updates to keep things fast.

Always commit or abort transactions to keep data safe and consistent.