MongoDB的.NET上没有产生UPSERT _id [英] MongoDB .NET not generating _id on upsert

查看:160
本文介绍了MongoDB的.NET上没有产生UPSERT _id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图UPSERT文档到2.4.4的MongoDB使用.NET的驱动程序。它似乎没有自动生成 _id 上upserts,尽管它正确生成 _id 在普通刀片。我怎么可能会导致驱动程序才能正常产生 _id



下面是演示该问题的一个小例子。

 公共类MongoObject 
{
[BsonId(IdGenerator = typeof运算(StringObjectIdGenerator))]
〔BsonRepresentation(BsonType.ObjectId)
公共字符串MongoID {搞定;组; }

公众诠释指数{搞定;组; }
}

VAR OBJ =新MongoObject()
{
指数= 1
};

//此插入文档,但与_id设置为NULL
_collection.Update(Query.EQ(指数,BsonValue.Create(1)),Update.Replace( OBJ),UpdateFlags.Upsert,新WriteConcern(){杂志=真});

//这将插入与预期自动生成的_id
//_collection.Insert(obj)的文件;


解决方案

当然,我马上找到了答案张贴之后,题。从这个答案,解决的办法就是添加一个 [BsonIgnoreIfDefault] 属性的ID。从问题的例子将是:



 公共类MongoObject 
{
[BsonId(IdGenerator = typeof运算(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)
[BsonIgnoreIfDefault] //< ---这就是失踪了
公共字符串MongoID {搞定;组; }

公众诠释指数{搞定;组; }
}


I'm attempting to upsert a document into MongoDB 2.4.4 using the .NET driver. It seems not to automatically generate the _id on upserts, though it does correctly generate the _id on plain inserts. How can I cause the driver to properly generate the _id?

Here is a small example that demonstrates the problem.

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);

解决方案

And of course I find the answer immediately after posting the question. From this answer, the solution is to add a [BsonIgnoreIfDefault] attribute to the ID. In the example from the question it would be:

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; }
}

这篇关于MongoDB的.NET上没有产生UPSERT _id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆