BrandUp.MongoDB
10.0.13
dotnet add package BrandUp.MongoDB --version 10.0.13
NuGet\Install-Package BrandUp.MongoDB -Version 10.0.13
<PackageReference Include="BrandUp.MongoDB" Version="10.0.13" />
<PackageVersion Include="BrandUp.MongoDB" Version="10.0.13" />
<PackageReference Include="BrandUp.MongoDB" />
paket add BrandUp.MongoDB --version 10.0.13
#r "nuget: BrandUp.MongoDB, 10.0.13"
#:package BrandUp.MongoDB@10.0.13
#addin nuget:?package=BrandUp.MongoDB&version=10.0.13
#tool nuget:?package=BrandUp.MongoDB&version=10.0.13
BrandUp.MongoDB
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
collModresize 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 mongod — BrandUp.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 | Versions 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. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Options (>= 10.0.9)
- MongoDB.Driver (>= 3.9.0)
- SharpCompress (>= 1.0.0)
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 | 224 | 5/28/2026 |
| 10.0.9 | 131 | 5/20/2026 |
| 10.0.8 | 140 | 5/12/2026 |
| 10.0.7 | 126 | 5/12/2026 |
| 10.0.6 | 133 | 5/5/2026 |
| 10.0.5 | 141 | 4/27/2026 |
| 10.0.4 | 160 | 4/20/2026 |
| 10.0.3 | 229 | 3/16/2026 |
| 10.0.2 | 172 | 3/11/2026 |
| 10.0.1 | 229 | 1/3/2026 |
| 8.0.9 | 505 | 7/14/2025 |
| 8.0.8 | 525 | 6/11/2025 |
| 8.0.3 | 371 | 3/29/2025 |
| 8.0.2 | 386 | 3/9/2025 |
| 8.0.1 | 322 | 12/22/2024 |
| 7.3.2 | 547 | 7/9/2024 |
| 7.3.1 | 320 | 7/9/2024 |
| 7.2.5 | 366 | 6/30/2024 |
| 7.2.3 | 456 | 4/29/2024 |