# How to Update a MongoDB Document Without Overwriting Someone Else's Change

> MongoDB optimistic concurrency in practice: $set only changed fields, filter on a version or original values, and read matchedCount to catch conflicts.

Source: https://bussolaformongo.app/blog/update-mongodb-document-without-overwriting/ · 2026-10-26

To update a MongoDB document without overwriting someone else's change, use optimistic concurrency: read the document, remember its `version` (or the original values of the fields you edit), then send an update whose filter includes that version and whose body uses `$set` and `$inc` on only the fields you changed. If the result has `matchedCount: 0`, someone else got there first, and you re-read and retry or ask the user. MongoDB has no built-in "compare the whole document" check, so the guard has to live in your filter.

## The lost update problem

Two people open the same order. Alice changes `status` to `"shipped"`. Bob changes `notes`. Both clients read the document, edit it locally, and write it back with `replaceOne`:

```js
// Alice's client
db.orders.replaceOne({ _id: orderId }, { _id: orderId, status: "shipped", notes: "", total: 120 })

// Bob's client, a few seconds later
db.orders.replaceOne({ _id: orderId }, { _id: orderId, status: "paid", notes: "call customer", total: 120 })
```

Bob's write replaces the entire document with his stale copy. Alice's `status` change is silently gone, and neither write returned an error. This is the classic read-modify-write race, and it is a property of whole-document replacement, not a MongoDB bug.

Single-document operations in MongoDB are atomic, so each write is internally consistent. The problem is that the decision (what to write) was made against data that changed before the write landed.

## Step 1: send only what changed with $set

The cheapest improvement is to stop replacing documents. Use `updateOne` with `$set` for the fields the user actually edited:

```js
db.orders.updateOne(
  { _id: orderId },
  { $set: { notes: "call customer" } }
)
```

Now Alice's `status` and Bob's `notes` both survive, because they touch different fields. This alone removes most accidental overwrites. It does not help when two people edit the same field, or when a change depends on the previous value (for example, "set status to shipped only if it is still paid").

For numeric changes that are relative, such as stock or counters, use `$inc` instead of reading and writing a computed number:

```js
db.products.updateOne({ _id: sku }, { $inc: { stock: -1 } })
```

The server applies the increment atomically, so there is no race to detect.

## Step 2: make the filter carry the expectation

To detect same-field conflicts, add the value you read to the filter. The update then only matches if the document is still in the state you saw:

```js
const res = db.orders.updateOne(
  { _id: orderId, status: "paid" },          // expectation: still "paid"
  { $set: { status: "shipped" } }
)

if (res.matchedCount === 0) {
  // someone changed it (or deleted it): re-read and decide
}
```

This is a compare-and-set. The check and the write happen in one atomic operation on the server, which is what makes it safe.

Things to know about filtering on original values:

- **Check every field you are changing**, not just one. Put the original values of all edited fields in the filter.
- **`null` matches missing fields.** `{ field: null }` matches documents where `field` is null or absent. That is usually what you want, but be aware of it.
- **Arrays and subdocuments compare exactly**, including element and key order. A filter on a whole embedded document fails if the key order differs. For these, prefer a version field.
- **Floating point and Int64 values** must round-trip exactly. If your client converts an Int64 to a JavaScript number and back, the filter may fail to match for large values; see [Why Your MongoDB Int64 Values Change in JavaScript](/blog/mongodb-int64-precision-javascript/).

## Step 3: use a version field for whole-document edits

When a form edits many fields at once, filtering on all original values gets unwieldy. Add an integer `version` (the name is up to you) and bump it on every write:

```js
// Read
const doc = db.orders.findOne({ _id: orderId })   // { ..., version: 7 }

// Write: succeed only if nobody wrote since we read
const res = db.orders.updateOne(
  { _id: orderId, version: 7 },
  {
    $set: { status: "shipped", notes: "left at door" },
    $inc: { version: 1 }
  }
)
```

Every writer must follow the convention, otherwise a writer that skips the `$inc` defeats the check. If some code paths cannot be changed, fall back to filtering on original values for those fields.

Documents that predate the field have no `version`. Filter on `{ version: null }` for the first write (it matches missing) and let `$inc` create the field as 1. `$inc` on a missing field treats it as 0.

## Reading the result: matchedCount vs modifiedCount

The result of `updateOne` has two counters that mean different things:

| Field | Meaning |
| --- | --- |
| `matchedCount` | Documents that satisfied the filter |
| `modifiedCount` | Documents whose content actually changed |

For conflict detection, **use `matchedCount`**. If you `$set` a field to the value it already has, `matchedCount` is 1 and `modifiedCount` is 0, which is not a conflict. A `matchedCount` of 0 means the filter no longer matches: the document was changed, or deleted, or you filtered on the wrong value.

That last point matters. `matchedCount: 0` cannot tell you *why*. To give a useful message, re-read the document:

```js
if (res.matchedCount === 0) {
  const current = db.orders.findOne({ _id: orderId })
  if (current === null) {
    // deleted
  } else {
    // changed: show current values, let the user merge or retry
  }
}
```

If you use upserts with this pattern, be careful: `{ upsert: true }` with a filter that fails on `version` will try to insert a new document with the same `_id` and fail with a duplicate key error, or create an unintended duplicate when `_id` is not in the filter. Do not combine upsert with optimistic checks unless you want that behavior.

## findOneAndUpdate: get the winning document back

When you want the new state in the same round trip, use `findOneAndUpdate`. By default it returns the document as it was *before* the update; set `returnDocument: "after"` to get the result:

```js
const updated = db.orders.findOneAndUpdate(
  { _id: orderId, version: 7 },
  { $set: { status: "shipped" }, $inc: { version: 1 } },
  { returnDocument: "after" }
)

if (updated === null) {
  // no match: conflict or deleted
}
```

Here a `null` return replaces the `matchedCount: 0` check. This is convenient for retry loops, because the caller gets the fresh document on success and can re-read on failure. In the Node.js driver, note that the return shape of `findOneAndUpdate` depends on the `includeResultMetadata` option and the driver version, so check what your version returns.

## A retry loop for automatic merges

If the changes are commutative or can be merged by the application, retry a bounded number of times:

```js
function updateWithRetry(id, mutate, maxAttempts = 5) {
  for (let i = 0; i < maxAttempts; i++) {
    const doc = db.orders.findOne({ _id: id })
    if (!doc) return { ok: false, reason: "deleted" }
    const changes = mutate(doc)                       // returns a $set object
    const res = db.orders.updateOne(
      { _id: id, version: doc.version },
      { $set: changes, $inc: { version: 1 } }
    )
    if (res.matchedCount === 1) return { ok: true }
  }
  return { ok: false, reason: "too many conflicts" }
}
```

Do not retry blindly when a human made the edit. Overwriting silently on retry reintroduces the lost update; surface the conflict instead.

## When you need more than a single document

Optimistic checks cover one document. If a business rule spans several documents, such as moving money between two accounts, use a multi-document transaction (replica sets and sharded clusters only; standalone servers do not support them) or redesign the data so that the invariant lives in one document. Transactions cost more than a filtered update, so reach for them only when a single-document guard cannot express the rule.

## Editing from a phone

The same pattern applies when you edit a document by hand from a client. Bussola's document editor saves only the fields you modified and detects a conflict if someone else edited the document in the meantime, which is the `$set` plus filtered-update approach described above. If you do edit production data from a phone, read [How to Safely Query a Production MongoDB From Your Phone](/blog/query-production-mongodb-from-phone-safely/) first, and keep read-only mode on unless you intend to write. See [Bussola](/) for details.

## Summary checklist

- Never `replaceOne` a document you read earlier unless the filter proves it has not changed.
- Use `$set` for the fields that changed and `$inc` for relative numeric changes.
- Put the original values, or a `version` field, in the update filter.
- Bump `version` with `$inc` on every write, from every writer.
- Detect conflicts with `matchedCount === 0`, not `modifiedCount`.
- Re-read after a miss to distinguish a deleted document from a changed one.
- Avoid `upsert: true` with optimistic filters.
- Use `findOneAndUpdate` with `returnDocument: "after"` when you need the resulting document.
- Use transactions only for invariants that span multiple documents.
