Table of Contents

Define entities

Add the import statement and create your entities by inheriting the Entity base class.

using MongoDB.Entities;

public class Book : Entity
{
    public string Title { get; set; }
}

Ignore properties

If there are some properties on entities you don't want persisted to mongodb, simply use the IgnoreAttribute. You can prevent null/default values from being stored with the use of IgnoreDefaultAttribute.

public class Book : Entity
{
    [Ignore] 
    public string DontSaveMe { get; set; }

    [IgnoreDefault] 
    public int SomeNumber { get; set; }
}

Customize field names

You can set the field names of the documents stored in mongodb using the FieldAttribute like so:

public class Book : Entity
{
    [Field("book_name")]
    public string Title { get; set; }
}

Customize collection names

By default, mongodb collections will use the names of the entity classes. You can customize the collection names by decorating your entities with the CollectionAttribute as follows:

[Collection("Writer")]
public class Author : Entity
{
    ...
}

Optional auto-managed properties

There are 2 optional interfaces ICreatedOn & IModifiedOn that you can add to entity class definitions like so:

public class Book : Entity, ICreatedOn, IModifiedOn
{
    public string Title { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime ModifiedOn { get; set; }
}

If your entity classes implements these interfaces, the library will automatically set the appropriate values so you can use them for sorting operations and other queries.

The IEntity interface

If for whatever reason, you're unable to inherit the Entity base class, you can simply implement the IEntity interface to make your classes compatible with the library like so:

public class Book : IEntity
{
    [BsonId]
    public string ID { get; set; } = null!;
}

Customizing the ID format

IDs for new entities are generated by the mongodb driver's IIdGenerator resolved for the entity's ID property. Out of the box, string IDs get ObjectId-formatted strings, and ObjectId and Guid IDs get new ObjectIds/Guids. If you'd like to change the type of the ID, simply declare the ID property with the type you want (decorated with [BsonId] when implementing IEntity):

public class Book : IEntity
{
    [BsonId]
    public Guid Id { get; set; } = Guid.Empty;
}

To customize how ID values are generated, register an IIdGenerator either for a single entity type (works for any entity, including ones inheriting their ID property from the Entity base class):

DB.RegisterIdGenerator<Book>(new MyCustomIdGenerator());

or for the CLR type of the ID (affects all entities with that ID type):

BsonSerializer.RegisterIdGenerator(typeof(long), new MySequentialLongIdGenerator());
Note

Do your registrations at application startup, before initializing database connections with DB.InitAsync(). Entity-level generators registered with DB.RegisterIdGenerator<T>() take precedence over class-map generators and ID-type-level generators, and can be registered any time (even after first use of the entity type). Class-map and BsonSerializer.RegisterIdGenerator registrations are only read when the entity type is first used, so they must be in place beforehand.

Note

The type of the ID property can be whatever type you like (given that it can be serialized by the mongo driver). Many<> one-to-many / many-to-many relationships support any ID type/representation, including string, long, ObjectId, Guid and custom-represented IDs such as [BsonRepresentation(BsonType.ObjectId)] string. Join records always store the ID exactly as it is stored in the entity's own _id field. One<TEntity> one-to-one references still use a string ID; for non-string IDs use the typed One<TEntity, TIdentity> instead. When using Guid IDs, register a Guid serializer before initializing the library, e.g. BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

Warning

Choose an ID generator that produces unique values. SaveAsync inserts when the entity has an empty ID and the library generates one, but uses a replacement upsert when the ID is already populated. Partial saves use update upserts. Reusing an existing ID can therefore overwrite data, regardless of the ID type. Use InsertAsync when an existing ID must cause a duplicate-key error rather than an update.

In v26, Entity.ID is an ObjectId-formatted string stored as a BSON string, not a BSON ObjectId. Existing databases using the old representation need compatibility mapping or data migration. See the v26 upgrade guide before deploying against existing data.

Create a collection explicitly

await db.CreateCollectionAsync<Book>(o =>
{
    o.Collation = new Collation("es");
    o.Capped = true;
    o.MaxSize = 1024 * 1024; // Required size limit in bytes for a capped collection.
    o.MaxDocuments = 10000;
});

Typically you don't need to create collections manually as they will be created automatically the first time you save an entity. However, you'd have to create the collection like above if you need to use a custom COLLATION, create a CAPPED, or TIME SERIES collection before you can save any entities.

Note

If a collection already exists for the specified entity type, an exception will be thrown.

Drop a collection

await db.DropCollectionAsync<Book>();