what is sleep
what is sleep

Reputation: 905

Atomically update multiple documents

In mongodb, I have the following command to update a bunch of documents

I am using mongodb-native driver for Node.js:

champion_statistics.bulkWrite([
    {updateOne: {filter: {id: 1}, update: {$inc: {sum: 2}}, upsert: false}},
    {updateOne: {filter: {id: 2}, update: {$inc: {sum: 5}}, upsert: false}}
], {
    ordered: false
}, function(err, res){
    //done
});

However, when I do a read, I find the collection in a state where the first operation finished but not the second operation. Is there something I can do to make multiple updates atomic?

Upvotes: 0

Views: 198

Answers (1)

wdberkeley
wdberkeley

Reputation: 11671

No. In MongoDB, operations are atomic only at the level of a single document. Multiple updates or updates affecting multiple documents always have the potential to yield in between changes to documents, allowing "intermediate state" reads to occur. Generally, atomicity requirements are built in to the document design, to the extent that's feasible. Beyond that, it is up to the application to enforce its atomicity requirement. Check out the docs article on 2-phase commits for an example of using application logic to enforce atomicity.

Upvotes: 1

Related Questions