mongodbmongodb-queryatomicwiredtiger

Atomicity in mongoDB updateOne


db.collection.updateOne(
  { _id: "unique_object_id", field_a:  5  },
  { $inc: { field_a: 1 } }
)

Let's suppose that in the collection, only one document has field_a equaling 5, ie, only one document matching the query above.

Questions:

  1. If there are two simultaneous instances of the above queries, is it possible that the end result after the two queries ended be that this document's field_a will be 7?

  2. Does the locking mechanism happens after matching the document? In other words, both queries will find and determine that this document is the one to update because neither has updated it yet, but one locks the document and increments field_a to 6, unlocks the document, and then the other query increments it to 7?

  3. Follow up of question 2, or does the second query performs an re-evaluation of the matching conditions after the lock has been released by the first query?

  4. Does findeOneAndUpdate follow the same rules and policies as updateOne in this scenario and atomicity in general?


Solution

  • Update operations on a single document are performed sequentially and atomically.

    Let's assume you're using updateOne. When MongoDB finds a document that meets the criteria, it creates a lock on the document. It then updates the document and relevant indexes before releasing the lock. This process happens at the database level and lasts for microseconds.

    1. If there are two simultaneous instances of the above queries, is it possible that the end result after the two queries ended be that this document's field_a will be 7? No, the first query will match the document and update it. The second query won't match this document because it was already updated and field_a is now 6.

    2. Does the locking mechanism happens after matching the document? In other words, both queries will find and determine that this document is the one to update because neither has updated it yet, but one locks the document and increments field_a to 6, unlocks the document, and then the other query increments it to 7? No, the update operation is atomic.

    3. Follow up of question 2, or does the second query performs an re-evaluation of the matching conditions after the lock has been released by the first query? Yes.

    4. Does findeOneAndUpdate follow the same rules and policies as updateOne in this scenario and atomicity in general? Yes, the only difference is that findOneAndUpdate returns the document.