Skip to content

Atomicity & Transactions

MongoDB Atomicity

A single document update is atomic. That fact drives a surprising amount of schema design.

IntermediateAbout 5 minutes

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() } }
)
One round trip, one document — always consistent

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?

Think about it first.