Stop 06 · MongoDB Data Modeling & AggregationTopics · 8/8

Transactions in MongoDB

Part of the MERN Stack Roadmap

In short

Placing an order means reducing stock and creating the order. If the server crashes between the two, you either sell stock you don't have or lose an order. A transaction makes both writes succeed together or not at all.

Multi-document transactions make several writes succeed or fail together, such as deducting stock and creating an order. They need a replica set, which Atlas provides.

The jaadu and a shopkeeper exchange a packet and a cloth money pouch across a counter at exactly the same moment, both holding on with both hands.

Think of it like this

Exchanging goods at the counter

At a shop counter, you hand over the money and the shopkeeper hands over the packet in one exchange. If either side backs out, everyone takes their thing back. Nobody walks away with both. A transaction is that all-or-nothing exchange for database writes.

Watch it happen

Placing an order in a transaction

API
products
orders
startSession + withTransaction

1/4The API opens a session and starts a transaction.

The big ideas

What you need to know

All or nothing

Every write in a transaction commits together, or none do. Other readers never see half the work.

Needs a replica set

Transactions require a replica set or sharded cluster. Every Atlas cluster, including the free tier, is a replica set.

Pass the session

Every operation inside must include { session }. Forget it and that write happens outside the transaction.

Single documents are already atomic

An update to one document never needs a transaction. Design your data so most writes touch one document.

See it in code

Walk through the code

js
1import { MongoClient } from "mongodb";2 3const client = new MongoClient(process.env.MONGODB_URI);4const db = client.db("shopdb");5 6export async function placeOrder(userId, productId, qty) {7  const session = client.startSession();8  try {9    return await session.withTransaction(async () => {10      const res = await db.collection("products").updateOne(11        { _id: productId, stock: { $gte: qty } },12        { $inc: { stock: -qty } },13        { session }14      );15      if (res.modifiedCount === 0) throw new Error("Out of stock");16 17      const order = { userId, productId, qty, status: "placed", createdAt: new Date() };18      await db.collection("orders").insertOne(order, { session });19      return order;20    });21  } finally {22    await session.endSession();23  }24}

1/5A session tracks which operations belong to the transaction.

withTransaction commits on success, aborts on any error and retries on temporary errors for you.

Save yourself the pain

Common mistakes

Oops

Forgetting { session } on one of the operations.

Do this instead

Pass the session to every read and write that belongs to the transaction.

Oops

Using transactions for every single update.

Do this instead

Single-document writes are atomic already. Use transactions only when several documents must change together.

Oops

Running slow work, like sending an email, inside the transaction.

Do this instead

Keep transactions short. Send emails or call other services after the commit.

Your mission

Transfer wallet points safely

~30 min

Quick check

Which situation actually needs a multi-document transaction?

Go deeper

  1. 1Write a transaction that creates an order and reduces stock, and abort it if stock is too low.
  2. 2Remember that single-document updates are already atomic without a transaction.
  3. 3Keep transactions short to avoid conflicts and timeouts.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge