简体   繁体   中英

Id of Upserted Mongo Document in C#

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 = 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM