0
0
MongodbConceptBeginner · 3 min read

What is Transaction in MongoDB: Explanation and Example

A transaction in MongoDB is a way to group multiple operations so they either all succeed or all fail together, ensuring data consistency. It works like a single unit of work that guarantees atomicity across multiple documents or collections.
⚙️

How It Works

Think of a transaction in MongoDB like a shopping cart checkout process. When you buy several items, you want all the payments and inventory updates to happen together or not at all. MongoDB transactions let you bundle multiple database operations so they act as one. If any step fails, MongoDB rolls back all changes, keeping your data safe and consistent.

Under the hood, MongoDB uses a mechanism to track all operations in the transaction. When you commit the transaction, MongoDB applies all changes atomically. If you abort, none of the changes are saved. This is especially useful when working with multiple documents or collections where partial updates could cause errors or inconsistent data.

💻

Example

This example shows how to use a transaction in MongoDB with the Node.js driver. It updates two documents in different collections as a single transaction.

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

async function runTransaction() {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const session = client.startSession();

    const usersCollection = client.db('shop').collection('users');
    const ordersCollection = client.db('shop').collection('orders');

    const transactionResults = await session.withTransaction(async () => {
      await usersCollection.updateOne(
        { username: 'alice' },
        { $inc: { balance: -100 } },
        { session }
      );

      await ordersCollection.insertOne(
        { username: 'alice', item: 'book', price: 100 },
        { session }
      );
    });

    if (transactionResults) {
      console.log('Transaction committed successfully.');
    } else {
      console.log('Transaction aborted.');
    }
  } finally {
    await session.endSession();
    await client.close();
  }
}

runTransaction().catch(console.error);
Output
Transaction committed successfully.
🎯

When to Use

Use transactions in MongoDB when you need to ensure multiple related operations succeed or fail together. This is important in financial applications, inventory management, or any case where partial updates could cause problems.

For example, when transferring money between accounts, you want to debit one account and credit another in one transaction. If one update fails, the whole transfer should fail to avoid losing money. Similarly, when placing an order, updating stock and recording the order should happen together.

Key Points

  • Transactions ensure atomicity across multiple operations.
  • They help maintain data consistency in complex updates.
  • MongoDB supports multi-document transactions starting from version 4.0.
  • Use transactions only when necessary, as they add overhead.

Key Takeaways

MongoDB transactions group multiple operations to succeed or fail as one.
They ensure data consistency across multiple documents or collections.
Transactions are useful in critical operations like payments or inventory updates.
MongoDB supports transactions from version 4.0 and later.
Use transactions carefully to avoid performance impact.