0
0
MongoDBquery~5 mins

Transaction isolation in MongoDB

Choose your learning style9 modes available
Introduction
Transaction isolation helps keep data safe and consistent when many people change the database at the same time.
When multiple users update the same data and you want to avoid conflicts.
When you need to make sure a group of changes all happen together or not at all.
When you want to prevent seeing half-finished changes from others.
When running bank transfers or inventory updates that must be accurate.
When you want to keep your data reliable during complex operations.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction({ readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } });
try {
  // your database operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Transactions in MongoDB use sessions to group operations.
The 'snapshot' read concern ensures you see a consistent view of data during the transaction.
Examples
Basic transaction with default isolation.
MongoDB
const session = client.startSession();
session.startTransaction();
// operations
await session.commitTransaction();
session.endSession();
Start a transaction with snapshot isolation to see a consistent view.
MongoDB
session.startTransaction({ readConcern: { level: 'snapshot' } });
Ensure writes are confirmed by most nodes before committing.
MongoDB
session.startTransaction({ writeConcern: { w: 'majority' } });
Sample Program
This example reduces stock for two products in one transaction. If any update fails, all changes are undone.
MongoDB
const { MongoClient } = require('mongodb');

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

  try {
    session.startTransaction({ readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } });

    await collection.updateOne({ name: 'apple' }, { $inc: { stock: -1 } }, { session });
    await collection.updateOne({ name: 'banana' }, { $inc: { stock: -1 } }, { 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
MongoDB transactions provide snapshot isolation, meaning you see data as it was at the start of the transaction.
Transactions can only run on replica sets or sharded clusters, not standalone servers.
Keep transactions short to avoid performance issues.
Summary
Transaction isolation keeps your data consistent when many changes happen at once.
MongoDB uses sessions and snapshot isolation for transactions.
Use transactions to group related changes so they all succeed or fail together.