undefinedfix
Sign in

Will mongodb $set generate dirty data when updating different fields in the same document

user2676140 edited in Mon, 06 Dec 2021

When mongodb $set updates different fields in the same document, dirty data will be generated. Under the condition of high concurrency, different fields may be updated at the same time, such as two people updating at the same time, a updating field 1 and B updating field 2. Can a be updated while B is also updated, and then the fields updated by a go back. An article said that $set is to update a field, which is atomic. But I didn't see this description in many places or authoritative places. Won't it cause the problem I mentioned above?

The mongodb modifier's $set by locknmeng is about to execute the following two sentences at the same time db.users.update ({"name":"mfw"},{"$set":{"addr":"shandong"}}) db.users.update ({"name":"mfw"},{"$set":{"mobile":"13333333333"}})

To correct, it has been confirmed that it is an atomic operation. I didn't read it carefully, but I still have some doubts. Does updating different fields at the same time affect me

1 Replies
kcomf
commented on Mon, 06 Dec 2021

Mongo's writing operations on a single document are always atomic

In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.When a single write operation modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic and other operations may interleave.
In Mongo, the write operation of a single document is always atomic, even if multiple nested documents in a single document are updated at the same time. When an operation updates multiple documents at the same time, the write operation of each single document is atomic, but the whole batch update operation is not atomic, and other operations may be interleaved

Reference: Mongo official document - atomicity and transactions

lock This question has been locked and the reply function has been disabled.