MongoDB Persistence (Community)

NuGet Package NServiceBus.Persistence.MongoDb (9.x) | License
This is a community maintained 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 allows resolution of configuration setting at run-time.

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

Via an app.config connection string

  <add name="NServiceBus/Persistence/MongoDB"

Override the default connection string name as follows:

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

Saga definition guideline

For sagas to work correctly, the following must 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 the 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 only one update to a saga will succeed if there are multiple simultaneous updates made to it.


Related Articles

Last modified