Atomicity & Transactions
MongoDB Atomicity
A single document update is atomic. That fact drives a surprising amount of schema design.
One updateOne against one document is atomic: every operator in that write is applied, or none of it is. Another reader never sees stock decremented and amount still the old value on the same order. That is why line items live on the order. Two documents — keyboard stock and a new order row — are not atomic with each other unless you open a transaction.
One document
- Atomic by default
- No session, no transaction
- order.items + order.amount + status
- The common MongoDB write
Two documents
- Not atomic by default
- Crash between writes = half-applied
- orders insert + products $inc
- Transaction, or live with the gap
db.orders.updateOne(
{ _id: orderId, status: "pending" },
{ $set: { status: "shipped", shippedAt: new Date() } }
)SQL people reach for BEGIN out of habit. Here you model first: if the fields must change together, put them on one document. Transactions exist (next lessons) and they cost locks, snapshot overhead, and a time limit. Wrapping a single-document $inc in a transaction is the mistake the last module of this track exists for.
Interview question
Does MongoDB support transactions, and when do you actually need them?
Yes — multi-document ACID transactions on replica sets (and sharded clusters). I need them far less than in SQL, because a single-document update is already atomic and related data is often embedded. Typical need: two documents must not be seen half-applied, like debiting one account and crediting another. If most writes sit in a transaction, the schema probably should have embedded more.