开发者

Id of Upserted Mongo Document in C#

开发者 https://www.devze.com 2023-04-12 20:52 出处:网络
It has been well documented how to get a return Id from an Insert to a MongoDb collection in C# (Example).But how do I get that for an upserted document?Is there a way, short of querying for the Id ag

It has been well documented how to get a return Id from an Insert to a MongoDb collection in C# (Example). But how do I get that for an upserted document? Is there a way, short of querying for the Id again, to use the SafeModeResult returned by an Update to find the upserted document Id?

My code:
var query = abc;
var update = 开发者_C百科xyz;
try
{
   db["Collection"].Update(query, update, UpdateFlags.Upsert);
}
catch
{
}


Solution found:

db["Collection"].FindAndModify(query, SortBy.Ascending(), update, true, true).Response.GetValue(1).AsBsonDocument.GetValue("_id")

returns the ObjectId.

0

精彩评论

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

关注公众号