Preparing your workspace
Transactions allow a group of supported database operations to be treated as one atomic unit.
Some application actions require multiple database changes to remain consistent. For example, creating a payment record and updating an associated order may need to succeed together. MongoDB supports transactions for supported deployment configurations. A transaction is started, operations are performed through the session, and the transaction is committed only when all required operations succeed. If something fails, the changes can be aborted. Transactions should be used when the business requirement actually needs atomic multi-document changes rather than for every operation.
An enrollment workflow may need to create an enrollment record and update a related seat or capacity record consistently.
const session = client.startSession();
try {
await session.withTransaction(async () => {
await db.collection("enrollments").insertOne(
{ studentId: "u1", courseId: "c1" },
{ session }
);
await db.collection("courses").updateOne(
{ _id: "c1" },
{ $inc: { enrolledCount: 1 } },
{ session }
);
});
} finally {
await session.endSession();
}Both related database operations are handled as one transaction and are committed together when successful.