MongoDB Persistence (Ryan Hoffman)

Project Hosting
NuGet Package NServiceBus.Persistence.MongoDb (9.x) | License
This is a community run project. License and support are independent of Particular Software.
Target NServiceBus Version: 6.x

Uses MongoDB for storage.

Includes MongoDB persistence implementations for


To use MongoDB for persistence


Connection Settings

There are several ways to set the MongoDB Connection

Via Code

This enables resolving configuration setting at run-time.

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

Via an app.config Connection String

  <add name="NServiceBus/Persistence/MongoDB"

The default connection string name can be override as follows:

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

Saga definition guideline

For Sagas to work correctly the following needs to be enforced:

  • Saga Data should implement IContainSagaData.
  • Requires a property Version decorated with attribute [DocumentVersion].

For example:

public class OrderBillingSagaData :
    public string OrderId { get; set; }

    public int Version { get; set; }

    public bool Canceled { get; set; }

Dealing with concurrency

The key concurrency safeguards that sagas guarantee depend heavily on the underlying data store. The two specific cases that NServiceBus relies on the underling data store are concurrent access to non-existing saga instances and concurrent access to existing saga instances.

Concurrent access to non-existing saga instances

The persister uses Unique Indexes to ensure only one document can contain the unique data.

Concurrent access to existing saga instances

The persister uses a document versioning scheme built on top of findAndModify command to atomically update the existing persisted data only if it has not been changed since it was retrieved. Since the update is atomic, it will ensure that if there are multiple simultaneous updates to a saga, only one will succeed.


Related Articles

Last modified