Id Member

Unique Identifier

Each top level document in MongoDB contains an _id field that uniquely identifies documents in the collection. This field can be mapped from/to a public property in C# models. By convention public members named Id, id and id will be used as the identifier. MongoDB will ensure to generate a value for your identifier field when inserting documents and deserialize it back your model member during reads.

circle-exclamation

Supported MongoDB Id generators

You can use the following types for your Id identifier type:

String

Let's assume that you have a Message class with a string Id public member:

IdMember.cs
var message = new Message {Text = "hello world"};

await messagesCollection.InsertOneAsync(message);

Utils.Log(message.ToBsonDocument());
triangle-exclamation

The correct way to use a string Id member as identifier field is the following:

circle-check

Guid

Guid is one of the most used types for identifying documents and MongoDB fully support them. In fact, in case you use it along with a convention compatible Id member, you don't even need to specify the IdGenerator.

COMB Guid

MongoDB supports generating Guid values using the COMB algorithm and you can use it as follow:

ObjectId

MongoDB loves ObjectId β™₯️ which is a 12-byte special type for MongoDB which is fast to generate and contains:

  • A timestamp value representing the ObjectId's creations (4-byte)

  • An auto-incrementing counter (3-byte)

  • A random value (5-byte)

circle-info

In fact, if you try to insert a document in MongoDB in the shell and don't provide any value for the _id field, it will be saved as an ObjectId type

Convention based names with ObjectId type don't require the [BsonId] attribute.

If you want to use a custom identifier name, just add the [BsonId] attribute. Defining the ObjectIdGenerator is optional.

BsonObjectId

Everything applies for the ObjectId type applies for BsonObjectId as well.

If you want to use a custom identifier name, just add the [BsonId] attribute. Defining the BsonObjectIdGenerator is optional.

NullIdChecker Generator

In case you want to ensure that the identifier field has been assigned a value before sending the query to MongoDB, you can use the NullIdChecker generator.

circle-exclamation

Last updated