MongoDB atomic update via 'merge' document

穿精又带淫゛_ 提交于 2019-12-04 13:49:30

问题


I know that I can atomically update an existing Mongo document by setting specific fields. The following code will do it:

var update = MongoDB.Driver.Builders.Update.Set("InsideLegMeasurement", 32.4);
SafeModeResult result = personCollection.Update(query, update, UpdateFlags.Multi,SafeMode.True);

However, can I atomically update several fields by passing in a document that I want to 'merge' with the existing doc? Imagine I have a document as follows: {"favcolor":"red","favfood":"pasta"} and I want to update an existing doc with these values. I want to do this:

var update = MongoDB.Driver.Builders.Update.Merge({"favcolor":"red","favfood":"pasta"});

or even

var update = MongoDB.Driver.Builders.Update.Merge(myUpdateBsonDoc);

where myBsonDocument contains lots of fields which I don't want to have to 'unpack' from the doc that is to be merged with the original.

Is this possible somehow?

Thanks


回答1:


Found the answer:

//var snippetJSON= '{title:"Tin Machine II",brandnewfield:"this gets added nicely"}';
    MongoDB.Bson.BsonDocument updateDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(snippetJSON);
var update = new UpdateDocument { { "$set", updateDoc } };

Easy when you know how!



来源:https://stackoverflow.com/questions/5965181/mongodb-atomic-update-via-merge-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!