MongoDB Integration
MongoDB Integration
Do define a separated
MongoDbContext
interface and class for each module.
MongoDbContext Interface
Do define an interface for the
MongoDbContext
that inherits fromIAbpMongoDbContext
.Do add a
ConnectionStringName
attribute to theMongoDbContext
interface.Do add
IMongoCollection<TEntity>
properties to theMongoDbContext
interface only for the aggregate roots. Example:
MongoDbContext class
Do inherit the
MongoDbContext
from theAbpMongoDbContext
class.Do add a
ConnectionStringName
attribute to theMongoDbContext
class.Do implement the corresponding
interface
for theMongoDbContext
class. Example:
Collection Prefix
Do add static
CollectionPrefix
property to theDbContext
class. Set default value from a constant. Example:
Used the same constant defined for the EF Core integration table prefix in this example.
Do always use a short
CollectionPrefix
value for a module to create unique collection names in a shared database.Abp
collection prefix is reserved for ABP core modules.
Collection Mapping
Do explicitly configure all aggregate roots by overriding the
CreateModel
method of theMongoDbContext
. Example:
Do not configure model directly in the
CreateModel
method. Instead, create an extension method for theIMongoModelBuilder
. Use ConfigureModuleName as the method name. Example:
Repository Implementation
Do inherit the repository from the
MongoDbRepository<TMongoDbContext, TEntity, TKey>
class and implement the corresponding repository interface. Example:
Do pass the
cancellationToken
to the MongoDB Driver using theGetCancellationToken
helper method. Example:
GetCancellationToken
fallbacks to the ICancellationTokenProvider.Token
to obtain the cancellation token if it is not provided by the caller code.
Do ignore the
includeDetails
parameters for the repository implementation since MongoDB loads the aggregate root as a whole (including sub collections) by default.Do use the
GetMongoQueryableAsync()
method to obtain anIQueryable<TEntity>
to perform queries wherever possible. Because;GetMongoQueryableAsync()
method automatically uses theApplyDataFilters
method to filter the data based on the current data filters (like soft delete and multi-tenancy).Using
IQueryable<TEntity>
makes the code as much as similar to the EF Core repository implementation and easy to write and read.
Do implement data filtering if it is not possible to use the
GetMongoQueryable()
method.
Module Class
Do define a module class for the MongoDB integration package.
Do add
MongoDbContext
to theIServiceCollection
using theAddMongoDbContext<TMongoDbContext>
method.Do add implemented repositories to the options for the
AddMongoDbContext<TMongoDbContext>
method. Example:
Notice that this module class also calls the static BsonClassMap
configuration method defined above.
Last updated