0
0
MongoDBquery~5 mins

Commit and abort behavior in MongoDB

Choose your learning style9 modes available
Introduction

Commit and abort control if changes to the database are saved or canceled. This helps keep data correct and safe.

When you want to save a group of changes only if all succeed.
When you want to cancel changes if something goes wrong.
When updating multiple documents and want all updates to apply together.
When you want to avoid partial updates that can cause errors.
When working with transactions to keep data consistent.
Syntax
MongoDB
const session = client.startSession();
await session.startTransaction();
try {
  // database operations
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}

Use startTransaction() to begin a transaction.

Use commitTransaction() to save changes.

Use abortTransaction() to cancel changes.

Examples
Insert a document and commit if successful, else abort.
MongoDB
const session = client.startSession();
await session.startTransaction();
try {
  await collection.insertOne({name: 'Alice'}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Update and delete documents in one transaction, commit if all succeed.
MongoDB
const session = client.startSession();
await session.startTransaction();
try {
  await collection.updateOne({name: 'Bob'}, {$set: {age: 30}}, {session});
  await collection.deleteOne({name: 'Charlie'}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Sample Program

This program starts a transaction, inserts a user, updates the user, and commits the changes. If any step fails, it aborts the transaction.

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

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

  const session = client.startSession();
  await session.startTransaction();

  try {
    await collection.insertOne({name: 'Diana'}, {session});
    await collection.updateOne({name: 'Diana'}, {$set: {age: 25}}, {session});
    await session.commitTransaction();
    console.log('Transaction committed');
  } catch (error) {
    await session.abortTransaction();
    console.log('Transaction aborted');
  } finally {
    session.endSession();
    await client.close();
  }
}

run();
OutputSuccess
Important Notes

Transactions work only on replica sets or sharded clusters in MongoDB.

Always end the session with endSession() to free resources.

Use transactions to keep multiple operations safe and consistent.

Summary

Commit saves all changes made in a transaction.

Abort cancels all changes made in a transaction.

Use transactions to group multiple operations safely.