Working with _id in .Net

Hi, David,

Documents in MongoDB must have an _id member, which uniquely identifies the document within a collection. The .NET/C# driver automatically adds an _id member if you don’t assign one explicitly. The driver automatically maps the Id property of a class to the _id field in the database. You can override this with class mapping attributes or code configuration if desired.

When a new document is inserted into a collection, it will use the value of the Id property if it is assigned. If not, it will generate a new Id using the configured IIdGenerator. The defaults work well for most users. If the Id property is an ObjectId, the ObjectIdGenerator will be used. If a string, then the StringObjectIdGenerator will be used. There are other generators and you can find additional details in our documentation on The Id Member.

For most applications, the default conventions work well without additional configuration. I would recommend starting with the following and let the defaults do their magic:

public class Animal
{
    public ObjectId Id { get; set; }
    // other properties and code
}

You can find more information on mapping classes in Mapping.

Hope that helps.

Sincerely,
James

2 Likes