Transactions in MongoDB
8 min read
Multi-Document Transactions
MongoDB supports ACID multi-document transactions on replica sets and sharded clusters (version 4.0+). Transactions let you group multiple operations so they either all succeed or all roll back — essential for operations like transferring credits between accounts.
js
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const session = client.startSession();
try {
session.startTransaction();
const db = client.db("school");
await db.collection("students").updateOne(
{ name: "Riya Sharma" },
{ $set: { enrolled: true } },
{ session }
);
await db.collection("payments").insertOne(
{ studentName: "Riya Sharma", amount: 15000, paidAt: new Date() },
{ session }
);
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
await client.close();
}Transactions add latency and resource overhead. Use them only when you genuinely need atomicity across multiple collections. For single-document operations, MongoDB is already atomic without a transaction.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises