0
0
MongodbHow-ToBeginner · 3 min read

How to Abort a Transaction in MongoDB: Syntax and Examples

To abort a transaction in MongoDB, use the abortTransaction() method on the session object. This stops all operations in the current transaction and rolls back any changes made during it.
📐

Syntax

The abortTransaction() method is called on a session object to cancel the current transaction. It must be called within an active transaction.

  • session: The client session that started the transaction.
  • abortTransaction(): Method that aborts the transaction and rolls back changes.
javascript
const session = client.startSession();
session.startTransaction();
// perform operations
await session.abortTransaction();
session.endSession();
💻

Example

This example shows how to start a transaction, perform an operation, and then abort the transaction to undo the changes.

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

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

  try {
    session.startTransaction();
    const collection = client.db('testdb').collection('testcol');

    await collection.insertOne({ name: 'Alice' }, { session });

    // Abort the transaction to undo the insert
    await session.abortTransaction();

    console.log('Transaction aborted, changes rolled back.');
  } finally {
    await session.endSession();
    await client.close();
  }
}

run().catch(console.dir);
Output
Transaction aborted, changes rolled back.
⚠️

Common Pitfalls

  • Calling abortTransaction() outside an active transaction causes errors.
  • Not ending the session after aborting can lead to resource leaks.
  • Forgetting to use the session object in operations inside the transaction means changes won't be part of the transaction.
javascript
/* Wrong way: aborting without starting a transaction */
const session = client.startSession();
try {
  await session.abortTransaction(); // Error: no active transaction
} finally {
  await session.endSession();
}

/* Right way: */
const session = client.startSession();
session.startTransaction();
// perform operations
await session.abortTransaction();
await session.endSession();
📊

Quick Reference

Remember these key points when aborting transactions in MongoDB:

  • Use abortTransaction() on the session object.
  • Only call it during an active transaction.
  • Always end the session after aborting.
  • Operations inside the transaction must include the session.

Key Takeaways

Use session.abortTransaction() to cancel and roll back a MongoDB transaction.
Always start a transaction with session.startTransaction() before aborting.
Include the session in all operations inside the transaction.
End the session with session.endSession() to free resources.
Calling abortTransaction() outside a transaction causes errors.