如何在更新MongoDB文档后获取_id?

时间:2016-02-10 14:01:59

标签: c# mongodb mongodb-.net-driver

我正在使用.Net MongoDB.Driver 2.2.3和MongoDB 3.2。我希望获得我用_id插入或替换的文档的collection.ReplaceOneAsync(),因为我稍后会使用它。

但是,如果操作是更新,则结果的UpsertedIdnull(如果发生插入,则设置为 )。

确定更新文档的_id的最佳方法是什么?

var collection = GetMongoDatabase().GetCollection<BsonDocument>("foos");
var document = new BsonDocument
{
     {"foo", "new bar"}
};
var result = await collection.ReplaceOneAsync(
    Builders<BsonDocument>.Filter.Eq("foo", "bar"),
    document,
    new UpdateOptions {IsUpsert = true});
// I want to use result.UpsertedId here;

如果我在Visual Studio的立即窗口中更新后查看result,我看到:

?result
{MongoDB.Driver.ReplaceOneResult.Acknowledged}
    [MongoDB.Driver.ReplaceOneResult.Acknowledged]: {MongoDB.Driver.ReplaceOneResult.Acknowledged}
    IsAcknowledged: true
    IsModifiedCountAvailable: true
    MatchedCount: 1
    ModifiedCount: 1
    UpsertedId: null

1 个答案:

答案 0 :(得分:2)

据我所知ReplaceOneAsync方法在替换文档时没有返回UpsertedId,您会在插入文档时看到带有值的字段。如果替换现有文档,则可以在数据库中检查替换文档是否与旧文档的_id相同:

var collection = GetMongoDatabase().GetCollection<BsonDocument>("foos");
var d=collection.Find<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "bar")).FirstOrDefault();
var id = d["_id"].ToString();//Check your id here
var document = new BsonDocument
{
     {"foo", "new bar"}
};
var result = await collection.ReplaceOneAsync(
             Builders<BsonDocument>.Filter.Eq("foo", "bar"),
             document,
             new UpdateOptions {IsUpsert = true});

var d1=collection.Find<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "new bar")).FirstOrDefault();
var id1 = d1["_id"].ToString(); // You will see the same _id

您正在寻找的方法可能是FindOneAndReplaceAsync

var d =collection.FindOneAndReplace<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "new bar"), 
                                                  document,
                                                  new FindOneAndReplaceOptions<BsonDocument, BsonDocument>() 
                                                  { IsUpsert=true,
                                                    ReturnDocument=ReturnDocument.After
                                                  });
var id = d["_id"].ToString();