Skip to main content

Transactions

Transactions in MongoDB allow you to execute multiple read and write operations atomically on one or more documents within a single session. This ensures data consistency and integrity, even in distributed systems. Transactions in MongoDB are similar to transactions in relational databases and offer ACID (Atomicity, Consistency, Isolation, Durability) properties.

Features of Transactions

  1. ACID Compliant: MongoDB transactions are ACID compliant, ensuring reliable and consistent data in your applications.

  2. Multi-Document: Transactions can span multiple documents, multiple collections, and multiple databases.

  3. Multi-Statement: Multiple read and write operations can be included in a single transaction.

  4. Nested Transactions: MongoDB supports nested transactions, allowing you to have transactions within transactions for more complex workflows.

  5. Rollback: If an error occurs during a transaction, all changes can be rolled back, leaving the data in a consistent state.

  6. Commit: Once all operations in the transaction are successfully executed, the changes can be committed, making them permanent.

How to Use Transactions

Here's a simple example using Node.js to demonstrate a transaction:

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

async function main() {
const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test";
const client = new MongoClient(uri);

try {
await client.connect();

const session = client.startSession();

session.startTransaction();

const ordersCollection = client.db('test').collection('orders');
const inventoryCollection = client.db('test').collection('inventory');

// Insert an order
await ordersCollection.insertOne({ item: "apple", qty: 10 }, { session });

// Update the inventory
await inventoryCollection.updateOne({ item: "apple" }, { $inc: { qty: -10 } }, { session });

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

main().catch(console.error);

In this example, an order for 10 apples is inserted into the orders collection, and the inventory collection is updated to reflect this. Both operations are part of a single transaction.

Considerations

  1. Performance: Transactions can add overhead, especially in sharded clusters. Use them judiciously and only when necessary.

  2. Timeout: Transactions have a default timeout, after which they are automatically aborted if not committed.

  3. Concurrency: While a transaction is in progress, write or update operations on the involved documents are locked, which might impact concurrency.

  4. Error Handling: Always include proper error handling to abort the transaction in case of failures.