AI agents: use the documentation index at llms.txt to locate machine-readable pages. This section is indexed by https://docs.particular.net/persistence/llms.txt. The markdown version of this page is served as plain text. An MCP server at /mcp serves the same content via the search_docs and read_doc tools; it is read-only and needs no credentials. Markdown versions of documentation pages are available by appending .md to the page URL. Directory URLs use index.md. They are served as text/plain because some retrieval backends reject text/markdown.

MongoDB Persistence

MongoDB persistence uses the MongoDB document database for storage.

Use a MongoDB server version that is compatible with the version of MongoDB.Driver your endpoint uses. See the MongoDB driver compatibility tables.

Persistence at a glance

For a description of each feature, see the persistence at a glance legend.

Feature
Supported storage typesSagas, Outbox, Subscriptions
TransactionsEnabled and required by default
Concurrency controlPessimistic locking for saga updates and deletes when transactions are enabled
Scripted deploymentNot supported
InstallersIndex creation depends on the persistence version

Usage

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

endpointConfiguration.UsePersistence<MongoPersistence>();

Customizing the connection

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

To customize the connection, pass a MongoClient configured with your connection string in place of SharedMongoUrl:

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>();
persistence.DatabaseName("DatabaseName");

Transactions

MongoDB persistence enables and requires transactions by default. Transactions let the persistence use pessimistic locking and commit updates to multiple saga instances atomically during message processing.

Disabling transactions

The following configuration API is available for compatibility with MongoDB server configurations that don't support transactions:

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

Note that this disables the ability to use pessimistic locking for sagas, which might result in higher contention in the database.

Shared transactions

NServiceBus supports sharing MongoDB sessions between Saga persistence, Outbox storage, and business data. The shared session can be used to persist multiple document updates atomically.

To access the shared session 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(), null, context.CancellationToken);
}

To access the session through dependency injection, use IMongoSynchronizedStorageSession:

class MyService
{
    IMongoSynchronizedStorageSession sharedSession;

    // Resolved from DI container
    public MyService(IMongoSynchronizedStorageSession sharedSession)
    {
        this.sharedSession = sharedSession;
    }

    public Task Create()
    {
        return sharedSession.MongoSession.Client
            .GetDatabase("mydatabase")
            .GetCollection<MyBusinessObject>("mycollection")
            .InsertOneAsync(sharedSession.MongoSession, new MyBusinessObject());
    }
}

Testing

The TestableMongoSynchronizedStorageSession class in the NServiceBus.Testing namespace has been provided to facilitate testing a handler that utilizes the shared transaction feature.

Outbox

Storage format

Outbox record documents are stored in a collection called outboxrecord.

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>();
persistence.TimeToKeepOutboxDeduplicationData(TimeSpan.FromDays(30));

Saga concurrency

Concurrent message handling can cause conflicts. See Saga concurrency for how NServiceBus handles these conflicts and for guidance on high-load scenarios.

Starting a saga

Example exception:

MongoDB.Driver.MongoCommandException: Command insert failed: WriteConflict.

Updating or deleting saga data

When transactions are enabled, MongoDB persistence uses exclusive locks for saga updates and deletes. It tries to acquire a lock for up to 60 seconds. If it cannot acquire one in that time, it throws a TimeoutException and the regular message retry policies apply.

Example exception:

System.TimeoutException: Unable to acquire exclusive write lock for saga on collection 'collectionName'

Installer

Installers are not supported. Indexes are created regardless of the installer settings.

List of Samples

Related Articles