Skip to content

Atomicity & Transactions

When to Use Transactions

Use them when two documents must change together. Do not use them as a default.

AdvancedAbout 5 minutes

Use a transaction when a reader must not observe a half-applied multi-document change. Ledger, dual-account transfer, 'order exists iff stock moved'. Do not use one because SQL used BEGIN, or to wrap a single $inc, or to paper over a schema that should have been one document.

Transaction

  • Two account balances
  • Order row + catalog stock must match
  • Invariant spans collections

No transaction

  • One order document (items embedded)
  • stock: { $gte: 1 }, $inc: -1
  • Rahul's city $set
  • Idempotent retries of a single write

Cost: extra round trips, WiredTiger snapshot, locks, abort on conflict, 60s cap, worse throughput under contention. If checkout always opens a txn that touches ten collections, embed or accept eventual (stock is a cache, order is source of truth, a job repairs). If you wrap updateOne on users in a session 'for ACID', you paid for a snapshot and got the same atomicity $set already had.

Interview question

When should you not use a MongoDB transaction?

Think about it first.