简体   繁体   English

C#中更新的Mongo文档的ID

[英]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 ). 在C#中,如何从Insert到MongoDb集合中获取返回ID已经得到了很好的证明( 示例 )。 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? 除了再次查询Id之外,是否有一种方法可以使用Update返回的SafeModeResult来找到上载的文档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. 返回ObjectId。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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