Search code examples
mongodbconcurrencyfindandmodify

MongoDB findOneAndUpdate Concurrent execution


I have a MongoDB Collection。 Schema:

{
    "_id": ObjectId 
    "status": String
}

Data:

{
    "_id": 1,
    "status": "waiting"
}

Thread A and Thread B Concurrent execute

findOneAndUpdate({"_id": "1", "status": "waiting"}, {$set: { "status": "running"}})

Although findOneAndUpdate is an atomic operation, is it possible to find the document simultaneously?

Thanks

I simulated 1000 threads for execution, and in the end only one thread output the document. But I'm not sure if I'm right


Solution

  • Updates are not inherently atomic in MongoDB.

    While updates use read-mutate-write, and multiple update processes can access the document at the same time, when it writes the changes to the storage engine, the query part is re-checked against the document, and if it no longer matches, the update is aborted with a write conflict.

    In your example, the query part matches against the same "status" field that is changed by the update part. This means that if there are multiple processes attempting to update, they will race to see which one completes first, but after one completes, all of the other updates already in progress will fail with a write conflict, and any that haven't fetched the document yet will not match the modified document at all.