Zanko
Zanko

Reputation: 4694

MongoDB Integrity Update edge case

Hello I have the following JSON in database,

{
   recordName : String
   amount : Number
   approved : Boolean
}

Lets say I have two users issue these two command at the same time

Record.update({recordName: "test", approved: false},{$set: {amount : 5000, approved: false,...)

Record.update({recordName: "test", approved: false},{$set: {amount : 9999, approved: true,...)

Does it always guarantee that the final results will always be amount 9999 and approve true?

I am worried that the final result might sometimes be amount 5000 and approve is false.

I am not really sure about MongoDB pipeline.

I believe update is splitted into two stages? Find {recordName: "test", approved: false} then update? What if both query already found the entry, then it all depends on who updates first?

Upvotes: 2

Views: 109

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

Because single document updates are atomic, regardless of the order that your two commands execute, the document will end up as:

{amount : 9999, approved: true, ...}

If the first command executes first, then the second command will override it.

If the second command executes first, then the first command has no effect as approve is now true so the update conditions won't match.

What you're (correctly) doing is the well-established optimistic concurrency or "update if current" approach to managing concurrent access.

Upvotes: 1

Related Questions