Skip to content

Concurrency

Concurrent Updates

Two requests, one document, and why last-write-wins is often not what you wanted.

AdvancedAbout 6 minutes

Two Node handlers can updateOne the same Rahul document at the same time. WiredTiger serialises those writes at the document. You do not get a torn document. You do get last-write-wins on any field both requests $set. Both calls return modifiedCount: 1. Nobody errors.

// A
db.users.updateOne({ name: "Rahul" }, { $set: { city: "Pune" } })
// B
db.users.updateOne({ name: "Rahul" }, { $set: { city: "Mumbai" } })
Request A and B — both succeed. City is whoever committed last.

$set the same field

  • Last commit wins
  • The other update vanished
  • city, name, a whole address object

$inc / $push

  • Both apply
  • stock 20 → 18 after two sales
  • skills gets both $push values

$set: { address: { city: "Pune" } } replaces the object. A concurrent $set: { "address.pin": "560001" } can disappear if the full address write lands second. Patch with dot paths ("address.city") when two writers own different keys. Isolation is not 'merge my JSON with theirs'. Isolation is 'one winner per field per $set'.

Interview question

What happens when two clients update the same MongoDB document at once?

Think about it first.