开发者

MongoDB: automatically generated IDs are zeroes

I'm using MongoDB and official C# driver 0.9

I'm just checking how embedding simple documents works.

There are 2 easy classes:

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

I create a new user:

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

collection.Insert(user.ToBsonDocument());

The u开发者_如何转开发ser is successfully saved, so is his address.

After typing

db.users.find()

in MongoDB shell, I got the following result:

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

Why is address' object id 0?

Doing queries with the address works though:

collection.FindOne(Query.EQ("Addresses.Street", streetName));

It returns the user "Sam".


It's not so much a bug as a case of unmet expectations. Only the top level _id is automatically assigned a value. Any embedded _ids should be assigned values by the client code (use ObjectId.GenerateNewId). It's also possible that you don't even need an ObjectId in the Address class (what is the purpose of it?).


Use BsonId attribute:

public class Address
{
    [BsonId]
    public string _id { get; set; }
    public string Street { get; set; }
    public string House { get; set; }
}

Identifying the Id field or property

To identify which field or property of a class is the Id you can write:

public class MyClass {
    [BsonId]
    public string SomeProperty { get; set; }
}

Driver Tutorial

Edit

It's actually not working. I will check later why. If you need get it work use following:

    [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());
    }


Get the collection as User type:

var collection = db.GetCollection<User>("users");

Initialize the field _id as follows:

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

Then you insert the object:

collection.InsertOne(user);

The _id field will automatically be generated.

In this link you will find alternative ways to have customized auto-generated ID(s).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜