BrandUp.MongoDB 10.0.13

dotnet add package BrandUp.MongoDB --version 10.0.13
                    
NuGet\Install-Package BrandUp.MongoDB -Version 10.0.13
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BrandUp.MongoDB" Version="10.0.13" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BrandUp.MongoDB" Version="10.0.13" />
                    
Directory.Packages.props
<PackageReference Include="BrandUp.MongoDB" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BrandUp.MongoDB --version 10.0.13
                    
#r "nuget: BrandUp.MongoDB, 10.0.13"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BrandUp.MongoDB@10.0.13
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BrandUp.MongoDB&version=10.0.13
                    
Install as a Cake Addin
#tool nuget:?package=BrandUp.MongoDB&version=10.0.13
                    
Install as a Cake Tool

BrandUp.MongoDB

Build Status

A thin, DI-friendly layer on top of the official MongoDB.Driver that gives you EF-style database contexts, automatic collection registration, conventions, transactions, and ergonomic test helpers.

Installation

NuGet: BrandUp.MongoDB

dotnet add package BrandUp.MongoDB

Define a context

Declare a class deriving from MongoDbContext. Each IMongoCollection<TDocument> property is auto-registered as a collection. Mark every document with [MongoCollection].

using BrandUp.MongoDB;
using MongoDB.Driver;

public class WebSiteDbContext : MongoDbContext, ICommentsDbContext
{
    public IMongoCollection<ArticleDocument> Articles => GetCollection<ArticleDocument>();
    public IMongoCollection<CommentDocument> Comments => GetCollection<CommentDocument>();
}

public interface ICommentsDbContext
{
    IMongoCollection<CommentDocument> Comments { get; }
}

[MongoCollection(CollectionName = "Articles")]
public class ArticleDocument { /* ... */ }

[MongoCollection(CollectionName = "Comments")]
public class CommentDocument { /* ... */ }

Register with DI

services.AddMongoDb(options =>
{
    options.ConnectionString = "mongodb://localhost:27017";
});

services
    .AddMongoDbContext<WebSiteDbContext>(options =>
    {
        options.DatabaseName = "WebSite";
    })
    .AddExtension<WebSiteDbContext, ICommentsDbContext>()
    .UseCamelCaseElementName()
    .UseIgnoreIfNull(true)
    .UseIgnoreIfDefault(false);

Resolve and use

var dbContext = serviceProvider.GetRequiredService<WebSiteDbContext>();
var commentsDbContext = serviceProvider.GetRequiredService<ICommentsDbContext>();

await dbContext.Articles.InsertOneAsync(new ArticleDocument { /* ... */ });

Transactions (await using)

MongoDbSession is registered per DI scope. ITransactionFactory and IClientSessionHandle are exposed alongside it. The transaction handle implements both IDisposable and IAsyncDisposable, so prefer await using — that flows the rollback path through AbortTransactionAsync instead of blocking the thread.

using var scope = serviceProvider.CreateAsyncScope();
var dbContext = scope.ServiceProvider.GetRequiredService<WebSiteDbContext>();
var transactionFactory = scope.ServiceProvider.GetRequiredService<ITransactionFactory>();
var session = scope.ServiceProvider.GetRequiredService<IClientSessionHandle>();

await using var transaction = await transactionFactory.BeginAsync(ct);

await dbContext.Articles.InsertOneAsync(session, new ArticleDocument { /* ... */ }, cancellationToken: ct);

await transaction.CommitAsync(ct);
// If CommitAsync is not reached (exception, early return), DisposeAsync aborts the transaction.

Collection parameters

Collection parameters can be declared right where the collection is registered — on the document — instead of being scattered across application start-up. Two complementary ways:

1. On the [MongoCollection] attribute (constants)

[MongoCollection(CollectionName = "events",
    Capped = true, CappedMaxSize = 16 * 1024 * 1024, CappedMaxDocuments = 100_000,
    ChangeStreamPreAndPostImages = true)]
public class EventDocument { /* ... */ }

2. On the document via IMongoCollectionConfiguration (full, programmatic)

Implement the interface to express anything the attribute can't — notably document validation. Declaring it on a base document applies the configuration to every derived document mapped to a collection.

[MongoCollection(CollectionName = "people")]
public class PersonDocument : IMongoCollectionConfiguration
{
    [BsonElement("name")] public string? Name { get; set; }

    public static void Configure(MongoCollectionConfigurationBuilder builder)
    {
        builder.Capped(maxSize: 16 * 1024 * 1024);
        builder.Validation(
            new BsonDocument("$jsonSchema", new BsonDocument
            {
                { "bsonType", "object" },
                { "required", new BsonArray { "name" } }
            }),
            DocumentValidationLevel.Strict,
            DocumentValidationAction.Error);
        builder.ChangeStreamPreAndPostImages();
    }
}

Only parameters MongoDB can change on an existing collection quickly (metadata-only, no scan or rewrite) are exposed: document validation, capped size/max, and change-stream pre/post images. Immutable options (collation, the capped flag itself, clustered index) and indexes — including TTL — are deliberately out of scope.

Updating already-existing collections

By default parameters are applied only when a collection is created. Enable UpdateExistingCollections to also reconcile declared parameters onto an existing collection (via the collMod command) when the context initializes. Only fields that actually differ are sent, so it is a no-op when nothing changed.

services.AddMongoDbContext<WebSiteDbContext>(options =>
{
    options.DatabaseName = "WebSite";
    options.UpdateExistingCollections = true;
});

Disabled by default to avoid unexpected schema changes against a live database. Note that MongoDB rounds a capped collection's size up to a multiple of 256 bytes — declare sizes on that boundary to avoid a harmless collMod resize on every start-up.

Escape hatch — raw driver options from DI

For environment-specific tweaks you can still reach the raw driver options. These hooks run after the declared parameters, so they win on conflict. configureCreate only fires when the collection is about to be created.

services
    .AddMongoDbContext<WebSiteDbContext>(options => options.DatabaseName = "WebSite")
    .ConfigureCollection<ArticleDocument>(
        configureSettings: s => s.ReadPreference = ReadPreference.SecondaryPreferred,
        configureCreate:   c => c.Capped = false);

Testing

In-memory fakes — BrandUp.MongoDB.Testing

NuGet: BrandUp.MongoDB.Testing

services.AddFakeMongoDb();

Fast and dependency-free; no MongoDB process required. Suitable when you only need the in-memory shape of the driver API — many advanced operators (aggregation, change streams, full filter pipelines) are intentionally not implemented.

Real mongodBrandUp.MongoDB.Testing.EphemeralMongo

NuGet: BrandUp.MongoDB.Testing.EphemeralMongo

services.AddEphemeralMongoDb();

Spins up a real ephemeral mongod (single-node replica set, so transactions work) via EphemeralMongo. Pick this for integration tests where you want the actual driver behaviour.

Legacy — BrandUp.MongoDB.Testing.Mongo2Go (deprecated)

The Mongo2Go-backed helper is still published for backwards compatibility but is no longer maintained upstream. Both AddTestMongoDb() and Mongo2GoDbClientFactory are marked [Obsolete]; please migrate to AddEphemeralMongoDb().

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on BrandUp.MongoDB:

Package Downloads
BrandUp.Pages.MongoDb

Package Description

BrandUp.MongoDB.Testing

Package Description

BrandUp.MongoDB.Testing.Mongo2Go

Package Description

BrandUp.Worker.MongoDB

Package Description

BrandUp.CardDav.Server

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.13 83 6/25/2026
10.0.12 226 5/28/2026
10.0.9 132 5/20/2026
10.0.8 141 5/12/2026
10.0.7 128 5/12/2026
10.0.6 134 5/5/2026
10.0.5 143 4/27/2026
10.0.4 161 4/20/2026
10.0.3 230 3/16/2026
10.0.2 173 3/11/2026
10.0.1 230 1/3/2026
8.0.9 506 7/14/2025
8.0.8 526 6/11/2025
8.0.3 372 3/29/2025
8.0.2 387 3/9/2025
8.0.1 324 12/22/2024
7.3.2 548 7/9/2024
7.3.1 322 7/9/2024
7.2.5 367 6/30/2024
7.2.3 457 4/29/2024
Loading failed