MongoDB:自动生成的ID为零
我正在使用MongoDB和官方C#驱动程序0.9
我只是在检查嵌入简单文档的工作原理。
有2个简单的课程:
public class User { public ObjectId _id { get; set; } public string Name { get; set; } public IEnumerable Addresses { get;set; } } public class Address { public ObjectId _id { get; set; } public string Street { get; set; } public string House { get; set; } }
我创建了一个新用户:
var user = new User { Name = "Sam", Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET" } }) }; collection.Insert(user.ToBsonDocument());
用户成功保存,他的地址也是如此。
打字后
db.users.find()
在MongoDB shell中,我得到以下结果:
{ "_id" : ObjectId("4e572f2a3a6c471d3868b81d"), "Name" : "Sam", "Addresses" : [ { "_id" : ObjectId("000000000000000000000000"), "Street" : "BIGSTREET", "House" : "BIGHOUSE" } ] }
为什么地址’对象ID为0?
使用该地址进行查询有效:
collection.FindOne(Query.EQ("Addresses.Street", streetName));
它返回用户“Sam”。
使用BsonId属性:
public class Address { [BsonId] public string _id { get; set; } public string Street { get; set; } public string House { get; set; } }
识别Id字段或属性
要确定类的哪个字段或属性是您可以编写的Id:
public class MyClass { [BsonId] public string SomeProperty { get; set; } }
驱动程序教程
编辑
它实际上不起作用。 我稍后会查看原因。 如果您需要让它工作使用以下:
[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()); }
这不是一个未满足期望的错误案例。 仅自动为顶级_id分配值。 应该通过客户端代码为任何嵌入的_id赋值(使用ObjectId.GenerateNewId)。 你也可能在Address类中甚至不需要ObjectId(它的目的是什么?)。
获取用户类型的集合:
var collection = db.GetCollection("users");
初始化字段_id如下:
var user = new User { _id = ObjectId.Empty, Name = "Sam", Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET" } }) };
然后插入对象:
collection.InsertOne(user);
将自动生成_id字段。
在此链接中,您将找到自定义自动生成ID的其他方法。