Skip to content
NServiceBus MongoDB persistence
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

NServiceBus.Storage.MongoDB MyGet (with prereleases)

This package includes MongoDB persistence implementations for NServiceBus v7:

  • Sagas
  • Outbox
  • Transactions


Add the NServiceBus.Storage.MongoDB package to your NServiceBus project.

Install-Package NServiceBus.Storage.MongoDB


1 Set the EndpointConfiguration object to use MongoPersistence:

using NServiceBus;

class Program
    public async Task Main()
        var endpointConfiguration = new EndpointConfiguration("Endpoint Name");

2 Hit F5. Assuming your MongoDB server is at mongourl://localhost:27017, it will just work.

Customizing the MongoDB connection

Provide a custom MongoClient by calling the .Client(client) method:

	.MongoClient(new MongoClient("Custom Mongo URL"));

Customizing the MongoDB connection

By default, the persistence will use the endpoint name as the database to store NServiceBus objects. Provide a custom database name by calling the .DatabaseName(name)method:



By default, the persistence will use session transactions for making changes to Saga data. This allows atomic guarantees when multiple sagas are invoked by a single message. To support older MongoDB servers (< 4) and MongoDB sharded clusters, you can disable transactions by calling the .UseTransactions(false) method:


You can join the existing MongoDB session transaction in your handlers by obtaining a reference to a database collection from the IMessageHandlerContext:

public Task Handle(MyMessage message, IMessageHandlerContext context)
    var collection = context.SynchronizedStorageSession().GetCollection<MyBusinessObject>("collectionname");    

The transaction and session will be automatically completed by NServiceBus when handler processing is complete.

Running tests locally

By default, both the AcceptanceTests and Tests projects will connect to any MongoDB server running at the default address of mongodb://localhost:27017.

To use a different Mongo URL, you can set the NServiceBusStorageMongoDB_ConnectionString environment variable.

Instructions for installing MongoDB can be found on the MongoDB website.

For developers using Docker containers, the following docker command will quickly setup a container configured to use the default port:

docker run -d -p 27017:27017 --name TestMongoDB mongo:latest --replSet tr0

Once started, initialize the replication set (required for transaction support) by connecting to the container:

docker exec -it TestMongoDB mongo

then use rs.initiate() to setup the replication set.


Documentation and samples can be found at

You can’t perform that action at this time.