itaied
itaied

Reputation: 7107

Is mongodb update with query atomic?

mongodb write and update opertaions are atomic, as stated in their docs.

But does it also atomic when using query?

For example:

db.collection.update( { id : 1 , count : 0 } , { $inc : { count : 1 } } )

If I execute this operation in a multi threaded environment, is it possible that at some point the value of count in the document with id equal to 1 will be greater than 1?

Upvotes: 7

Views: 3232

Answers (2)

RavinderSinghPB
RavinderSinghPB

Reputation: 149

in the documentation, atomicity is not mentioned about db.collection.update with query.

instead findAndModify() have mentioned with atomic behavior.

db.myCollection.findAndModify( { query: { ...},update: {....}})

refrence findAndUpdate doc link.

Upvotes: 0

kevinadi
kevinadi

Reputation: 13775

Any modification to a single document is atomic.

Using your example, let's say there are two threads trying to update that document using the same query:

Thread A: db.collection.update({_id: 1, count: 0}, {$inc: {count: 1}})
Thread B: db.collection.update({_id: 1, count: 0}, {$inc: {count: 1}})

with the collection containing the document:

collection: {_id: 1, count: 0}

If thread A managed to update the document before thread B, the collection would then contain:

collection: {_id: 1, count: 1}

Thread B will search for a document matching _id:1, count:0 but since that document was already modified by thread A, the update in thread B will not proceed (since the document no longer "exists" as thread B is concerned).

In other words, thread A will return nMatched: 1, nModified: 1, and thread B will return nMatched: 0, nModified: 0.

To specifically answer your question, there will not be a case where a document {_id: 1, count: 2} will exist.

Upvotes: 11

Related Questions