Is there a potential race condition here?

Say I have the following example doc:

{
  "name": "Jimmy Maxwell",
  "phone": "555-123-4567",
  "address": "123 Fake Street"
}

Say I have two independent operations: one that updates the phone number, and one that updates the address. These two operations are called concurrently (using an async library) at the same time:

db.person.updateOne({"name": "Jimmy Maxwell"}, {"$set": {"phone": "555-765-4321"}})
db.person.updateOne({"name": "Jimmy Maxwell"}, {"$set": {"address": "321 Maple Ave"}})

Is there a potential race condition such that either the phone or address won’t be set properly, or is it safe given that the updates only touch their respective fields?

“In MongoDB, an operation on a single document is atomic.”
See Transactions

1 Like