MongoDB:自动生成的ID为零

Ale*_*lex 18 c# embedding mongodb

我正在使用MongoDB和官方C#驱动程序0.9

我只是检查嵌入简单文档的工作原理.

有2个简单的课程:

public class User
{
    public ObjectId _id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Address> Addresses { get;set; }
}

public class Address
{
    public ObjectId _id { get; set; }
    public string Street { get; set; }
    public string House { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个新用户:

var user = new User
{
    Name = "Sam",
    Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET" } })
};

collection.Insert(user.ToBsonDocument());
Run Code Online (Sandbox Code Playgroud)

用户成功保存,他的地址也是如此.

打字后

db.users.find()
Run Code Online (Sandbox Code Playgroud)

在MongoDB shell中,我得到以下结果:

{ "_id" : ObjectId("4e572f2a3a6c471d3868b81d"), "Name" : "Sam",  "Addresses" : [
        {
                "_id" : ObjectId("000000000000000000000000"),
                "Street" : "BIGSTREET",
                "House" : "BIGHOUSE"
        }
] }
Run Code Online (Sandbox Code Playgroud)

为什么地址'对象ID为0?

使用地址进行查询有效:

collection.FindOne(Query.EQ("Addresses.Street", streetName));
Run Code Online (Sandbox Code Playgroud)

它返回用户"Sam".

Rob*_*tam 24

这不是一个未满足期望的错误案例.仅自动为顶级_id分配值.应该通过客户端代码为任何嵌入的_id赋值(使用ObjectId.GenerateNewId).你也可能在Address类中甚至不需要ObjectId(它的目的是什么?).

  • @UpTheCreek,只有根文档在集合的默认索引中编入索引,因此只有根文档需要唯一的ID. (2认同)

And*_*ich 13

使用BsonId属性:

public class Address
{
    [BsonId]
    public string _id { get; set; }
    public string Street { get; set; }
    public string House { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

识别Id字段或属性

要确定类的哪个字段或属性是您可以编写的ID:

public class MyClass {
    [BsonId]
    public string SomeProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

驱动程序教程

编辑

它实际上不起作用.我稍后会查看原因.如果您需要让它工作使用以下:

    [Test]
   public void Test()
    {
        var collection = Read.Database.GetCollection("test");

        var user = new User
        {
            Name = "Sam",
            Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET", _id = ObjectId.GenerateNewId().ToString() } })
        };

        collection.Insert(user.ToBsonDocument());
    }
Run Code Online (Sandbox Code Playgroud)

  • 还有一个错误到今天?任何更新? (2认同)