0
0
MongodbHow-ToBeginner · 4 min read

How to Use Transaction in MongoDB: Syntax and Example

In MongoDB, use session.startTransaction() to begin a transaction and session.commitTransaction() to save changes or session.abortTransaction() to cancel. Transactions allow multiple operations to be executed atomically across one or more collections.
📐

Syntax

To use transactions in MongoDB, you first start a client session, then start a transaction on that session. Perform your database operations within the transaction, and finally commit or abort the transaction.

  • startSession(): Creates a session to group operations.
  • startTransaction(): Begins the transaction.
  • commitTransaction(): Saves all changes made in the transaction.
  • abortTransaction(): Cancels all changes made in the transaction.
javascript
const session = client.startSession();
session.startTransaction();
try {
  // Perform operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
💻

Example

This example shows how to transfer money between two accounts atomically using a transaction. If any operation fails, the transaction aborts and no changes are saved.

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

async function runTransaction() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const session = client.startSession();

    const accounts = client.db('bank').collection('accounts');

    session.startTransaction();

    const fromAccount = { accountId: 1 };
    const toAccount = { accountId: 2 };
    const transferAmount = 100;

    // Subtract from sender
    await accounts.updateOne(
      fromAccount,
      { $inc: { balance: -transferAmount } },
      { session }
    );

    // Add to receiver
    await accounts.updateOne(
      toAccount,
      { $inc: { balance: transferAmount } },
      { session }
    );

    await session.commitTransaction();
    console.log('Transaction committed successfully');

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

runTransaction();
Output
Transaction committed successfully
⚠️

Common Pitfalls

Common mistakes when using MongoDB transactions include:

  • Not using sessions to group operations, so transactions don't work.
  • Forgetting to commit or abort the transaction, leaving it open.
  • Running transactions on standalone MongoDB servers; transactions require replica sets or sharded clusters.
  • Performing long-running operations inside transactions, which can cause performance issues.

Always ensure your MongoDB deployment supports transactions and keep transactions short.

javascript
/* Wrong: No session used, so no transaction */
db.collection('accounts').updateOne({ accountId: 1 }, { $inc: { balance: -100 } });
db.collection('accounts').updateOne({ accountId: 2 }, { $inc: { balance: 100 } });

/* Right: Use session and transaction */
const session = client.startSession();
session.startTransaction();
try {
  await accounts.updateOne({ accountId: 1 }, { $inc: { balance: -100 } }, { session });
  await accounts.updateOne({ accountId: 2 }, { $inc: { balance: 100 } }, { session });
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
📊

Quick Reference

  • startSession(): Begin a session for transactions.
  • startTransaction(): Start the transaction.
  • commitTransaction(): Save all changes.
  • abortTransaction(): Cancel all changes.
  • endSession(): Close the session.
  • Transactions require replica sets or sharded clusters.
  • Keep transactions short for best performance.

Key Takeaways

Always use sessions to start and manage transactions in MongoDB.
Commit transactions to save changes or abort to cancel all operations.
Transactions require MongoDB replica sets or sharded clusters, not standalone servers.
Keep transactions short to avoid performance issues.
Use transactions to ensure multiple operations succeed or fail together atomically.