C# – Is it appropriate to use id-s in MongoDb subdocuments

cmongodbnosql

I'm currently familiarizing myself with NoSQL by building a simple web application using MongoDb with the official C# driver. If i have understood the NoSQL concept correctly, then only the aggregate root document should have an id and the child collections are without identity.

For example in C# code i would have the following 2 Poco-s:

public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; } 
}

public class Pet
{
    public string Name { get; set; }
}

How would i solve a case, where i want to have separate CRUD views for pets? With a relational database i would do this by having the pet id in the query string, with NoSQL i'm not sure.

This question arose from when i tried to add an Id field to the "Pet" subdocument. Instead of an id for pet, an object named "_csharpnull" was added to the database instead.

For example if i do this:

public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; } 
}

public class Pet
{
    public BsonObjectId Id { get; set; }
    public string Name { get; set; }
}

Then this document is inserted into the database:

{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [ 
        {
            "_id" : {
                "_csharpnull" : true
            },
            "Name" : "T-Rex"
        }
    ]
}

When my expected behavior would be something like:

{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [ 
        {
            "_id" : ObjectId("56439adc766bcf49a0639992"),
            "Name" : "T-Rex"
        }
    ]
}

Best Answer

While I am not aware of a particular standard that says yes or no, in my experience this can and should in many cases be done.

The moment you want to be able to handle a Pet on it's own in various operations you need an ID. The simplest way in MongoDB is to just give it an ObjectID.

But I also have run into cases where this was not needed, such as when you have a sub document which always appears together with it's main document.

While I am not familiar with C# particularly, what you are trying to do definitely works in Java. Just make sure you actually initialize the ObjectID manually. While MongoDB creates object IDs for you on the top level documents of a collection it will not do the same for child documents.

Related Topic