开发者

MongoDB atomic update via 'merge' document

I know that I can atomically upda开发者_JS百科te 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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜