Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 70 ยท Transactions and consistency

Atomicity and Single-Document Writes

Understand why a single-document write in MongoDB is atomic, how atomic operators avoid race conditions, and how optimistic concurrency with a version field works.

When two users click "buy" at the same moment, two requests reach your database at the same moment. What happens next depends on whether your writes are atomic: either they happen completely, or not at all, and no other operation can see them half done. MongoDB gives you a strong, simple guarantee here: a write to a single document is atomic, even if it changes several fields and nested arrays at once.

This lesson explains what that guarantee covers, why it is the reason embedding works so well, how the update operators avoid the classic lost-update race, and how a version field gives you optimistic concurrency when you have to read, think and then write. The real syntax appears in mongosh blocks; the TryIts are JavaScript stand-ins that interleave two "clients" so you can see the race (see The Practice Engine Used in This Tutorial).

What is atomic

One document All fields change together or not at all.
Embedded data Arrays and subdocuments are part of it.
No half states Readers never see a partial update.

Across several documents, atomicity needs a transaction.

1 / 2

Single-document atomicity

Imagine an order document with a status, a total and an array of items. This update changes three places at once:

JavaScript
db.orders.updateOne(
  { _id: "o1", status: "pending" },
  {
    $set: { status: "paid", paidAt: new Date() },
    $push: { history: { event: "paid" } },
    $inc: { "totals.paid": 1 }
  }
)

Either all of it is applied, or none of it. A concurrent reader sees the order before or after, never with the status changed but the history missing. Behind the scenes MongoDB locks at the document level for the write, so two writers to the same document take turns, while writers to different documents run in parallel.

This is the main reason the document model often avoids multi-document transactions altogether: if everything that must change together lives in one document (an order with its items, an account with its balance and its recent movements), then one updateOne is already an all-or-nothing operation. Think of it as a modeling goal: when a consistency requirement keeps coming up, try to put the involved data in one document (Embedding vs Referencing).

The read-modify-write race

Atomicity of one write does not protect a sequence of operations. Consider selling the last item in stock with this code:

JavaScript
const item = await db.items.findOne({ _id: "mug" })       // 1. read: stock is 1
if (item.stock > 0) {
  await db.items.updateOne({ _id: "mug" }, { $set: { stock: item.stock - 1 } })  // 2. write
}

Each call is fine on its own, but there is a gap between step 1 and step 2. If two requests run step 1 before either runs step 2, both see stock: 1, both decide to sell, and both write 0. You have sold the same mug twice, and the stock never went negative, so nothing looks wrong. This is a lost update. Note that the problem is not in MongoDB: any database behaves this way if the logic reads, decides in application code and writes back.

The stand-in below simulates two customers whose requests interleave at the await. The first version is the naive read-then-set. The second version moves the check and the change into one atomic operation, which is the real MongoDB findOneAndUpdate with a filter on the stock and $inc.

JS Lost update versus atomic operator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the naive version both customers buy the single mug. In the atomic version exactly one succeeds. The real-MongoDB form of the winning approach is:

JavaScript
const result = await db.items.updateOne(
  { _id: "mug", stock: { $gt: 0 } },   // the condition is part of the filter
  { $inc: { stock: -1 } }
)
if (result.modifiedCount === 1) { /* you got it */ } else { /* sold out */ }

The filter and the update are applied atomically to the document, so only one request can match when stock is 1. The same trick works for any "if it is still in the expected state, then change it" rule: move an order from pending to paid only { status: "pending" }, claim a job only { claimedBy: null }, and so on. $inc, $push, $addToSet, $min and $max (Updating Documents, Updating Arrays) are also atomic and need no read first, so counters never lose increments.

Optimistic concurrency with a version field

Sometimes you cannot express the change as one operator: a user opens a profile editor, spends two minutes typing, and saves a whole new version of the document. If someone else saved in the meantime, you would overwrite their changes. The usual fix is optimistic concurrency control: add a version number, and make the save conditional on the version you originally read.

JavaScript
const doc = await db.profiles.findOne({ _id: "u1" })       // { _id: "u1", bio: "...", version: 4 }
// ... the user edits ...
const res = await db.profiles.updateOne(
  { _id: "u1", version: doc.version },                      // only if nobody changed it
  { $set: { bio: "new bio" }, $inc: { version: 1 } }
)
if (res.matchedCount === 0) { /* conflict: reload, merge or ask the user, then retry */ }

It is called optimistic because nothing is locked while the user thinks. You assume a conflict is unlikely, and you detect it cheaply when it happens. The next TryIt runs two editors against one document.

JS Optimistic concurrency with a version field

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Leo's first save matches nothing, because the document is now at version 2. Rather than silently overwriting Mia's bio, he reloads and retries, and both changes end up in the document. In a real application the retry step may be automatic (when the changes do not overlap) or may show the user a "this was changed by someone else" message.

Choosing the right tool

  • One change, expressible as an operator: use $inc, $push, $set and friends, with a conditional filter when you need a guard. No read, no race.
  • Read, decide, write back a whole document: use a version field (or compare another field such as updatedAt).
  • Several documents must change together or not at all: use a transaction, or remodel so they share one document.
  • Safe to run twice (retries): make operations idempotent with $set, $addToSet or a unique request id, a theme the inventory project returns to.

One caveat: single-document atomicity applies to the write on the primary. How durable the acknowledged write is, and what other clients can read, are set by write and read concerns (Read and Write Concerns).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is guaranteed to be atomic in MongoDB without a transaction?

    A write to a single document is atomic, including its nested fields and arrays. Separate calls, and updateMany across many documents as a whole, are not one atomic unit.
  2. 2. Two requests read stock: 1, both check stock > 0 and both write stock: 0. What is this called?

    The gap between the read and the write lets both requests act on the same old value, so one update overwrites the other's effect.
  3. 3. How does updateOne({ _id, stock: { $gt: 0 } }, { $inc: { stock: -1 } }) prevent overselling?

    The check lives in the filter of the same atomic write, so there is no gap in which another request can slip in.
  4. 4. In optimistic concurrency with a version field, what does matchedCount: 0 mean?

    The filter includes the version you read. If it no longer matches, another writer incremented it first, so you must reload and decide how to merge.

Summary

  • A write to one document is atomic, including all its fields, subdocuments and arrays; writers to the same document take turns.
  • That is why embedding related data often removes the need for transactions.
  • A read, decide, write sequence is not atomic: two clients can act on the same old value (a lost update).
  • Move the check into the filter and use atomic operators like $inc so the database does check and change in one step.
  • For whole-document edits, add a version field, write with { _id, version } in the filter and $inc: { version: 1 } in the update, and retry when matchedCount is 0.
  • Several documents that must change together need a transaction or a remodel.
  • The TryIts are JavaScript stand-ins for the behaviour; the mongosh code is real MongoDB.

Next, see what happens when one document is not enough in Multi-Document Transactions.