Reputation: 79
I'm a Mongodb beginner, I have a document like this:
{
"_id": "abc",
"names": {
"1" : "name1",
"2" : "name2",
"3" : "name3"
}
}
I want to use multithread add 'name4', 'name5', 'nameX'... to "names"
My way:
I know this is not atomic -_-!! so My question is How To Make It Atomic?
My another way: add a 'version' field to document, when Get the results, record the 'version', then Set the 'names' with the 'version' like :
update_one({"_id": "abc", "version": currentVersion}, {$set: {"names": newNames}})
If it does not match the 'version', the update failed, new 'nameN' will not add to the document. I want it to success any time.
Can someone help me? thanks
Upvotes: 1
Views: 338
Reputation: 8718
MongoDB only guarantees transaction on a document-level.
For your requirements you must guarantee the atomicity at the application-level using thread synchronization.
Upvotes: 1