MongoDB Persistence

NuGet Package NServiceBus.Storage.MongoDB (2-pre)
Target NServiceBus Version: 7.x
This page targets a pre-release version and is subject to change prior to the final release.

Uses the MongoDB document database for storage.

NServiceBus.Storage.MongoDB supports MongoDB server versions 3.6 and higher

Supported persistence types


Add a NuGet package reference to NServiceBus.Storage.MongoDB. Configure the endpoint to use the persistence through the following configuration API:


Customizing the connection

By default, a MongoClient is created that connects to mongodb://localhost:27017 and uses the endpoint name as its database name. This default connection is used for all the persisters.

Customize the server, port, and authentication database using the following configuration API:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.MongoClient(new MongoClient("SharedMongoUrl"));

Specify the database to use for NServiceBus documents using the following configuration API:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();

Multi-document transactions

Multi-document transactions are enabled and required by default. This allows the package to support updating multiple saga instances and commit them all atomically during message processing.

MongoDB transactions are only supported on MongoDB server replica sets.

Disabling transactions

The following configuration API is available for compatibility with MongoDB server versions less than 4 or for use with sharded clusters:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();

Shared transactions

NServiceBus supports sharing the same MongoDB session transaction between Saga persistence and business data. A single session transaction can be used to persist document updates for both concerns atomically.

To use the shared transaction in a message handler:

public Task Handle(MyMessage message, IMessageHandlerContext context)
    var session = context.SynchronizedStorageSession.GetClientSession();
    var collection = session.Client.GetDatabase("mydatabase").GetCollection<MyBusinessObject>("mycollection");
    return collection.InsertOneAsync(session, new MyBusinessObject());
In order to participate in the shared transaction the MongoDB session must be passed into collection API calls as demonstrated above.

Outbox cleanup

When the outbox is enabled, the deduplication data is kept for seven days by default. To customize this time frame, use the following API:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();


Related Articles

Last modified