How to atomically update two documents in a collection in MongoDB
I have a collection of documents that have this structure:
{ "name": "abc", "version": 1, "official": true, "someOtherField": {} }
In this collection, there can be no two documents with the same name and version combination (an index takes care of that). Also, for a given name, there can be at most 1 document where official is true.
Suppose my collection contains the following documents:
{"name": "abc", "version": 1, "official": false, ...}
{"name": "abc", "version": 2, "official": true, ..."}
{"name": "abc", "version": 3, "official": false, ..."}
Or, alternatively, is there a better way to model all of this? We will often be querying for all the {"official": true} documents, so I thought that keeping that information is the collection made sense. But maybe a better approach would be to keep a separate collection indicating what the official version for a given name is, such as
{"name": "abc", "official_version": 3}
In that case, changing the official version could be done simply by updating the appropriate official_version field, although there would be no guarantee that that version still exists in the main collection. Also, querying for all the official documents would require one or more operations, one to get a list of all name and official versions and another to get the actual documents from the main collection, which doesn't seem appropriate.
Thanks!
EDIT: as pointed out, there's no way to atomically update more than one document (see MongoDb doc). That being the case, it seems like the only way to atomically change the official version would be to track that information in a separate document, as outlined at the end of my post. Would still be interested in hearing about better alternatives, if anyone can think of any. Thanks
链接地址: http://www.djcxy.com/p/61952.html上一篇: 原子更新或推送元素