MongoDB .NET在upsert上不生成_id

Bri*_*chl 13 c# mongodb mongodb-.net-driver

我正在尝试使用.NET驱动程序将文档插入MongoDB 2.4.4.它似乎不会自动生成_idon upsert,虽然它确实正确生成了_idon plain插入.如何让驱动程序正确生成_id

这是一个展示问题的小例子.

public class MongoObject
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    [BsonRepresentation(BsonType.ObjectId)]
    public string MongoID { get; set; }

    public int Index { get; set; }
}

var obj = new MongoObject()
{
    Index = 1
};

//This inserts the document, but with a _id set to Null
_collection.Update(Query.EQ("Index", BsonValue.Create(1)), Update.Replace(obj), UpdateFlags.Upsert, new WriteConcern() { Journal = true });

//This inserts the document with the expected autogenerated _id
//_collection.Insert(obj);
Run Code Online (Sandbox Code Playgroud)

Bri*_*chl 21

当然,我在发布问题后立即找到答案.从这个答案,解决方案是向[BsonIgnoreIfDefault]ID 添加属性.在问题的例子中它将是:

public class MongoObject
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonIgnoreIfDefault]    // <--- this is what was missing
    public string MongoID { get; set; }

    public int Index { get; set; }
}
Run Code Online (Sandbox Code Playgroud)