Transactions, and Why You'll Need Them Less
When two shoppers reach for the last bike, a conditional updateOne keeps the stock right on its own, and when the stock and a new order must change together, a transaction makes both changes happen or neither.
Journeyman · MongoDB · Updated
After this lesson you can
- Write a conditional updateOne with $inc that takes stock only when enough is left, and read modifiedCount to see whether it did
- Write a transaction in mongosh with startSession and withTransaction, and predict what it changes when a write inside it fails
- Explain why transactions need a replica set, and why keeping changes in one document makes them rare
Key takeaways
- A write to one document is all or nothing, so a filter with stock $gte 1 and an $inc of -1 can never sell a bike that isn't there.
- After a conditional update, modifiedCount says who got it. 1 means this checkout took the bike, and 0 means someone else got there first.
- A transaction groups writes to several documents, and when any write in it fails, every change in it is undone.
- Transactions need a replica set. A standalone server refuses them, and Atlas's free cluster is already a replica set.
- Keeping what changes together in one document is why most apps need a transaction only now and then.
A checkout button, the last seat on a flight, the last ticket to a show: when two people reach for the same last thing at once, the database has to make sure only one of them gets it. You'll need this in any app that sells, books or reserves.
The examples use a small set of Riverbend Bike Shop's data that this chapter keeps for itself, with its own names and ids: not the catalog from Copying a Few Fields: the Extended Reference Pattern. Its products have a stock field, how many of a product the shop has. To follow along, start mongosh, type use riverbend, empty products, and add three products. The catalog's rules from Schema Validation with $jsonSchema would refuse this chapter's bike, which has no frame sizes, so drop() clears them too; load("riverbend-catalog.js") puts the catalog back any time:
db.products.drop()
db.products.insertMany([
{ _id: 1, name: "Riverbend Cruiser", type: "bike", price: NumberDecimal("649.00"), stock: 1 },
{ _id: 2, name: "Trailhead Helmet", type: "helmet", price: NumberDecimal("59.00"), stock: 12 },
{ _id: 3, name: "Beam 400 Light", type: "light", price: NumberDecimal("34.00"), stock: 3 }
])
true
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
Two shoppers, one bike
Maya and Leo both open the Riverbend Cruiser's page at 8:00 p.m., and the shop has one left. A first try at checkout reads the stock and, if it's 1 or more, takes one away:
db.products.findOne({ _id: 1 }, { name: 1, stock: 1 })
{ _id: 1, name: 'Riverbend Cruiser', stock: 1 }
Both checkouts read it at the same moment, see 1, and take one away with $inc (read "increment") and -1. Run this line twice, once for Maya and once for Leo:
db.products.updateOne({ _id: 1 }, { $inc: { stock: -1 } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Now read the stock again:
db.products.findOne({ _id: 1 }, { name: 1, stock: 1 })
{ _id: 1, name: 'Riverbend Cruiser', stock: -1 }
Two orders, one bike, and a stock of -1. Neither line is wrong on its own: the trouble is the gap between reading and writing, where another shopper slips in. That's a race condition, where the result depends on who gets there first.
One document is all or nothing
A deli counter's ticket roll never gives two people the same number, because tearing off a ticket and reading it happen in one motion. MongoDB makes every write to one document work the same way: the check and the change are one step, and no other write lands in between. That's atomicity (read "at-uh-MISS-ih-tee"): all of the change happens, or none of it.
So move the check into the update's filter. Put the stock back with db.products.updateOne({ _id: 1 }, { $set: { stock: 1 } }), then run Maya's checkout:
db.products.updateOne({ _id: 1, stock: { $gte: 1 } }, { $inc: { stock: -1 } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Read the filter aloud: "product 1, if its stock is greater than or equal to 1". Leo's checkout runs the same line a moment later:
{
acknowledged: true,
insertedId: null,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 0
}
The stock was 0 by then, so nothing matched. Even when both buttons are pressed at once, the server runs one update, then the other. The app reads modifiedCount: 1 means the bike is Maya's, so it writes her order; 0 means Leo sees "Sorry, that one has sold out". The stock never goes below zero.

A transaction: both changes or neither
A checkout changes two documents: the product's stock and a new order in orders. If the app stops between the two writes, say the network drops, a helmet leaves the stock with no order for it. A transaction groups several writes so that they all happen or none do. In mongosh:
const session = db.getMongo().startSession()
const shop = session.getDatabase("riverbend")
session.withTransaction(() => {
const taken = shop.products.updateOne({ _id: 2, stock: { $gte: 1 } }, { $inc: { stock: -1 } })
if (taken.modifiedCount === 0) { throw new Error("Sold out") }
shop.orders.insertOne({
_id: 1004, customerId: 7, status: "placed",
lines: [ { productId: 2, name: "Trailhead Helmet", price: NumberDecimal("59.00"), quantity: 1 } ]
})
})
Uncaught MongoServerError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Line by line: startSession() opens a session, a conversation with the server that a transaction belongs to, and const names it. shop is the riverbend database seen through that session. withTransaction(() => { ... }) runs everything inside the braces as one transaction: the conditional update takes a helmet, and if it took nothing, throw stops with the error Sold out, which undoes the transaction. Then the order goes in.
That's the answer from the server you installed in Setup: MongoDB, mongosh and Compass. Ignore its advice: your server runs on its own, and transactions need a replica set.
Practice on a one-member replica set
A replica set is a group of MongoDB servers that keep copies of the same data. One, the primary, records every write in a log; the others copy from it, so the data survives when a machine fails. Transactions are built on that log, so they need a replica set, even one with a single member. Atlas's free cluster, from Another Way: A Free Cluster on MongoDB Atlas, already is one.
On your computer, start a practice one beside the server you already have. Open a second terminal in your mongodb-course folder. On Windows, run:
mkdir practice-replica-set
& "C:\Program Files\MongoDB\Server\9.0\bin\mongod.exe" --replSet rs0 --port 27018 --dbpath practice-replica-set
On a Mac:
mkdir practice-replica-set
mongod --replSet rs0 --port 27018 --dbpath practice-replica-set
The server keeps printing log lines: leave that terminal open, and press Ctrl+C in it when you're done. In your first terminal, connect with mongosh --port 27018 and turn the server into a replica set:
rs.initiate()
{
info2: 'no configuration specified. Using a default configuration for the set',
me: 'localhost:27018',
ok: 1
}
The prompt changes to rs0 [direct: primary] test>. Type use riverbend, run this lesson's insertMany again, and paste the transaction block. It prints nothing, which means it worked:
db.products.findOne({ _id: 2 }, { name: 1, stock: 1 })
{ _id: 2, name: 'Trailhead Helmet', stock: 11 }
Now suppose a bug gives the next checkout the same order number. Paste only the session.withTransaction(...) part again:
Uncaught MongoServerError: E11000 duplicate key error collection: riverbend.orders index: _id_ dup key: { _id: 1004 }
The helmet was taken, then the order failed, and the whole transaction was undone. The stock is still 11:
db.products.findOne({ _id: 2 }, { name: 1, stock: 1 })
{ _id: 2, name: 'Trailhead Helmet', stock: 11 }
Why you'll need them less
Transactions cost something: a replica set, extra work for the server, other writes waiting their turn, and a 60-second limit by default. So keep what changes together in one place. An order with its line items embedded, as in Embedding: Keeping Related Data Together, is one document, so adding a line or changing its address is all or nothing with no transaction.
Stock is the exception: it belongs to the product, which many orders share, so a checkout touches two documents, and the transaction adds the promise that no checkout stops halfway. In a well-modeled app, most writes touch one document, and transactions are kept for the few places, such as checkout and cancel, where two must change together.
Check yourself
2 questions to try on the lesson page.
So what
You can now sell the last bike to exactly one person, and keep a stock change and its order together when both must happen. That's the difference between a store that's right on a quiet day and one that's right on its busiest.