MongoDbRepositoryCore 4.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MongoDbRepositoryCore --version 4.0.0
                    
NuGet\Install-Package MongoDbRepositoryCore -Version 4.0.0
                    
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="MongoDbRepositoryCore" Version="4.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbRepositoryCore" Version="4.0.0" />
                    
Directory.Packages.props
<PackageReference Include="MongoDbRepositoryCore" />
                    
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 MongoDbRepositoryCore --version 4.0.0
                    
#r "nuget: MongoDbRepositoryCore, 4.0.0"
                    
#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 MongoDbRepositoryCore@4.0.0
                    
#: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=MongoDbRepositoryCore&version=4.0.0
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbRepositoryCore&version=4.0.0
                    
Install as a Cake Tool

📖 MongoDbRepository Developer's Guide (v4.0.0)

Welcome to the daily cookbook for the MongoDbRepository framework. This guide covers how to leverage the advanced V4.0 features like AI Semantic Search, Microservices Caching, the Outbox Pattern, and Code-First Migrations.


1. Generative AI & Vector Search (New in V4.0)

MongoDB Atlas supports native AI Vector Searches. This library reduces the complex aggregation pipelines into a single attribute and method call.

Step 1: Add the [VectorEmbedding] attribute to a float[] property on your entity. The repository will automatically provision the Atlas Search Indexes on startup.

public class SupportArticle : Entity
{
    public string Title { get; set; }
    public string Content { get; set; }

    [VectorEmbedding(Dimensions = 1536, Similarity = "cosine")]
    public float[] ContentEmbedding { get; set; } 
}
Step 2: Execute a Semantic Search natively.

C#
// Generate embedding via OpenAI, HuggingFace, etc.
float[] userQuestionVector = await _aiService.GetEmbeddingAsync("How do I reset my password?");

// Search, with optional pre-filtering!
var topArticles = await _articleRepo.SemanticSearchAsync(
    queryVector: userQuestionVector, 
    limit: 5, 
    filter: article => article.IsActive // Pre-filters using standard LINQ
);
(Note: You can fully unit test this! The InMemoryRepository contains a native C# Cosine Similarity math engine that executes locally in 0ms!)

2. The Transactional Outbox Pattern (Guaranteed Events)
In a distributed system, saving a database record and firing an event (like sending a welcome email) is dangerous. If the server crashes between the two, the event is lost.

V4.0 uses the Transactional Outbox Pattern.

When you attach an event using IHasDomainEvents and save the entity, the repository serializes the MediatR event into a System_Outbox MongoDB collection inside the exact same ACID transaction.
A background worker then safely leases the message, fires the MediatR event, and retries up to 5 times on failure. Processed messages are automatically deleted via MongoDB TTL indexes after 7 days.

Usage: Just add the event and save. The library guarantees 100% delivery.

C#
user.AddDomainEvent(new UserRegisteredEvent(user.Id));
await _userRepo.AddAsync(user); 
3. Distributed Cluster Caching (Redis)
If you run multiple instances of your API (e.g., in Kubernetes), standard RAM caching leads to stale data. V4.0 introduces the DistributedCachingRepositoryDecorator.

By registering your repository with .AddDistributedCachedRepository<T, TId>(), the library will use Microsoft's IDistributedCache. If Pod A updates a user, it deletes the key from Redis, meaning Pods B, C, and D instantly fetch fresh data on their next request!

Configure your app name to prevent cross-API key collisions in a shared Redis cluster:

C#
builder.Services.AddMongoDbRepositories(db => { ... }, cache => 
{
    cache.ApplicationName = "BillingApi"; 
});
4. Code-First Migrations
Need to seed an Admin user or rename a property across 1 million documents? Write a migration script. The framework will automatically run it on application startup and track its execution in the System_Migrations collection.

C#
public class Migration_001_SeedAdmin : IMongoMigration
{
    public int Version => 1;

    public async Task UpAsync(IMongoDatabase database)
    {
        var users = database.GetCollection<User>("users");
        await users.InsertOneAsync(new User { Email = "admin@system.com", Role = "SuperAdmin" });
    }
}
5. Mockless Unit Testing
Stop mocking IMongoCollection and IAsyncCursor! We ship a blazing-fast, thread-safe fake that implements IRepository<T, TId> and executes your queries in memory.

C#
[Fact]
public async Task GetActiveUsers_ReturnsCorrectData()
{
    // 1. Arrange: Use the fake repository (0 milliseconds execution!)
    var fakeRepo = new InMemoryRepository<User, Guid>();
    fakeRepo.Seed(new[] {
        new User { Id = Guid.NewGuid(), IsActive = true, Name = "Alice" }
    });

    var service = new UserService(fakeRepo);

    // 2. Act
    var activeUsers = await service.GetActiveUsersAsync();

    // 3. Assert
    Assert.Single(activeUsers); 
}
6. The "Magic" Attributes Refresher
[Cacheable(Seconds = 3600)]: Automatically caches reads in RAM or Redis.

[AuditHistory]: Automatically tracks all BSON diffs to System_AuditLogs.

[Version]: Enables Optimistic Concurrency Control (prevents Last-Write-Wins).

[TimeSeries(nameof(Timestamp))]: Provisions native MongoDB columnar storage for logs.

[SecureString]: Encrypts PII fields natively before saving to the database.
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.4 102 5/14/2026
5.0.3 94 4/30/2026
5.0.2 96 4/25/2026
5.0.1 89 4/23/2026
5.0.0 109 4/21/2026
4.5.10 108 4/13/2026
4.5.4 102 4/10/2026
4.5.3 95 4/9/2026
4.5.2 96 4/9/2026
4.5.1 99 4/9/2026
4.1.0 100 4/9/2026
4.0.0 109 3/25/2026
3.4.5 112 3/20/2026
3.4.0 100 3/20/2026
3.3.0 109 3/20/2026
3.2.2 111 3/15/2026
3.2.1 107 3/15/2026
3.2.0 111 3/14/2026
3.1.0 108 3/6/2026
3.0.2 111 3/1/2026
Loading failed