Mongo DB 2.0驱动程序C# - Upsert - 生成对象ID

时间:2016-01-03 04:08:31

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

如果文档存在使用以下

,我可以更新文档
var filter = Builders<Neighborhood>.Filter.Eq(x => x.Id, neighborhood.Id);

var result = await collection.ReplaceOneAsync(filter,
             neighborhood,new UpdateOptions { IsUpsert = true });


[CollectionName("neighborhoods")]
[BsonIgnoreExtraElements(true)]
public class Neighborhood : IEntity<string>
{
 [BsonId(IdGenerator = typeof(GuidGenerator))]
 [BsonRepresentation(BsonType.ObjectId)]
 public string Id { get; set; }

 [BsonElement("name")]
 public string  Name    { get; set; }
}

如果Id = NULL并且我想返回更新的结果,如何插入文档。

当插入新文档时,使用NULL ID创建记录,我添加了[BsonId(IdGenerator = typeof(GuidGenerator))],但没有任何运气。

我做错了什么,因此可以为新记录生成ObjectId。

1 个答案:

答案 0 :(得分:2)

C#Driver认为Id已经填满。您需要为Id字段添加设置,以允许驱动程序生成新的Id 有两种方法:

  1. [BsonIgnoreIfDefault]模型中添加属性Neighborhood
  2. 代码设置

    BsonClassMap.RegisterClassMap<Neighborhood>(x =>
    {
        x.AutoMap();
        x.GetMemberMap(m => m.Id).SetIgnoreIfDefault(true);
    });
    
  3. 我更喜欢第二种方法,因为您不需要添加对MongoDB的引用。

    MongoDB API提出了两种方法:
    1)ReplaceOneAsync返回ReplaceOneResult具有UpsertedId属性

    var filter = Builders<Neighborhood>.Filter.Where(x => x.Name == "somthing"); var replaceResult = await collection.ReplaceOneAsync(filter, entity, new UpdateOptions { IsUpsert = true }); return replaceResult.UpsertedId;
    FindOneAndReplaceAsync

    2)var filter = Builders<Neighborhood>.Filter.Where(x => x.Name == "somthing"); var options = new FindOneAndReplaceOptions<Neighborhood, Neighborhood> { IsUpsert = true, ReturnDocument = ReturnDocument.After }; var updatedEntity = await collection.FindOneAndReplaceAsync(filter, entity, options); 允许您在更改之前或之后选择您想要的内容。对于我们的任务,我们需要

    {{1}}