Concurrency
Concurrent Updates
Two requests, one document, and why last-write-wins is often not what you wanted.
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" } })$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?
Each updateOne is atomic; the document is never half-applied. For $set on the same field, last commit wins and the other value is gone — both calls still succeed. $inc and $push from both clients both take effect. replaceOne of a document you read earlier overwrites fields you never meant to touch.