0
0
MongoDBquery~5 mins

Session and transaction syntax in MongoDB

Choose your learning style9 modes available
Introduction

Sessions and transactions help you group multiple database actions so they happen together or not at all. This keeps your data safe and correct.

When you want to update several documents and ensure all updates succeed or none do.
When transferring money between two accounts and you need both debit and credit to happen together.
When inserting related data in multiple collections and want to avoid partial data.
When you want to keep your database consistent during complex operations.
When you want to retry operations safely if something goes wrong.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  // database operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Use startSession() to begin a session.
Wrap your operations between startTransaction() and commitTransaction() or abortTransaction().
Examples
Starts a session and transaction, inserts a document, commits the transaction, then ends the session.
MongoDB
const session = client.startSession();
session.startTransaction();
await collection.insertOne({name: 'Alice'}, {session});
await session.commitTransaction();
session.endSession();
Updates two documents inside a transaction. If any update fails, the transaction is aborted.
MongoDB
const session = client.startSession();
try {
  session.startTransaction();
  await collection.updateOne({name: 'Alice'}, {$set: {age: 30}}, {session});
  await collection.updateOne({name: 'Bob'}, {$set: {age: 25}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Sample Program

This program starts a session and transaction, inserts a user, updates the user's age, then commits the transaction. If any step fails, it aborts the transaction.

MongoDB
async function runTransaction(client) {
  const session = client.startSession();
  try {
    session.startTransaction();
    const coll = client.db('testdb').collection('users');
    await coll.insertOne({name: 'John', age: 28}, {session});
    await coll.updateOne({name: 'John'}, {$set: {age: 29}}, {session});
    await session.commitTransaction();
    console.log('Transaction committed');
  } catch (error) {
    await session.abortTransaction();
    console.log('Transaction aborted');
  } finally {
    session.endSession();
  }
}

// Assume client is connected MongoClient
runTransaction(client);
OutputSuccess
Important Notes

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

Transactions only work on replica sets or sharded clusters, not standalone servers.

Pass the session object to all operations inside the transaction.

Summary

Sessions group operations for transactions.

Transactions ensure all-or-nothing execution.

Use startSession(), startTransaction(), commitTransaction(), and abortTransaction() properly.