MongoDbRepositoryCore 6.4.3

dotnet add package MongoDbRepositoryCore --version 6.4.3
                    
NuGet\Install-Package MongoDbRepositoryCore -Version 6.4.3
                    
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="6.4.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbRepositoryCore" Version="6.4.3" />
                    
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 6.4.3
                    
#r "nuget: MongoDbRepositoryCore, 6.4.3"
                    
#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@6.4.3
                    
#: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=6.4.3
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbRepositoryCore&version=6.4.3
                    
Install as a Cake Tool

📖 MongoDbRepository v6.4 (.NET 10 & C# 13)

Welcome to the production runtime engine for MongoDbRepository v6.4.3. Fully optimized for .NET 10 and C# 13, this core framework provides an explicit, high-performance data access layer built directly on top of the official MongoDB C# Driver v3.10.0.

Version 6.4.3 delivers hardened multi-tenancy isolation (dynamic collection-per-tenant resolution & tenant-isolated caching), native BSON binary vectors for Atlas Vector Search, hybrid search reranking via $rankFusion, first-class .NET 10 DateOnly/TimeOnly BSON serialization, bidirectional keyset pagination, automatic Time-Series collection provisioning, and transactional schema migrations.


🌟 Core Pillars of Enterprise Hardening

1. Hardened Domain Immutability

Domain entity definitions enforce strict data integrity constraints. Primary identifier properties utilize native C# init accessors, completely eliminating downstream key mutations and ensuring client-side domain models align with database-level primary key immutability rules.

2. Thread-Safe Ambient Transactions

Multi-document mutations share database execution contexts across async stack continuations safely using an AsyncLocal session handle. Internal modifications are protected by a localized coordination gate (LockObject), ensuring thread-safe processing inside parent transaction contexts. Furthermore, an explicit fallback boundary timeout (maxCommitTime) prevents long-running pipeline locks from stalling connection pools.

3. Single-Roundtrip Atomic Upserts ($setOnInsert, $set, $inc)

The repository's UpsertAsync method is fully optimized to eliminate TOCTOU race conditions in a single atomic database roundtrip.

  • IAuditableEntity: Sets CreatedAt on insertion via $setOnInsert without overwriting existing timestamps on updates, and $set: UpdatedAt.
  • IVersionedEntity: Uses $inc: { Version: 1 } to atomically initialize versioning to 1 on insertion and increment on update while enforcing optimistic concurrency version checks.
  • In-Memory Sync: Automatically updates document.CreatedAt, document.UpdatedAt, and document.Version on the caller's in-memory instance post-upsert.

ISemanticSearchRepository encodes vector embeddings as compact BsonBinaryData using BsonBinarySubType.Vector (Dense Float32). This reduces vector payload size by 4x compared to BSON double arrays and accelerates Atlas Vector Search queries.

5. Hybrid Search Reranking ($rankFusion)

Combines text search ($search) and vector search ($vectorSearch) in a single pipeline using the MongoDB 9.0 / Driver 3.10.0 $rankFusion aggregation stage for state-of-the-art Reciprocal Rank Fusion (RRF) reranking.

6. First-Class .NET 10 DateOnly & TimeOnly Support

Includes DateOnlyBsonSerializer and TimeOnlyBsonSerializer registered globally in CoreDomainMappingProfile, seamlessly mapping .NET 10 DateOnly ("yyyy-MM-dd") and TimeOnly ("HH:mm:ss.fffffff") primitives to BSON.

7. Time-Series Collection Provisioning (ITimeSeriesEntity)

Entities implementing ITimeSeriesEntity and decorated with [BsonTimeSeries(TimeField = ..., MetaField = ..., Granularity = ...)] are automatically created as native MongoDB Time-Series collections on application boot via AddAutomatedIndexes.

8. Binary SHA256 & Tagged Cache Invalidation

  • Query Cache: Uses binary SHA256 hashing (CacheKeyBuilder.ComputeQueryHash) to bypass JSON stringification overhead.
  • Tagged Eviction: Supports fine-grained tagged cache invalidation (InvalidateTagCache(tag)), avoiding collection-wide flushes when invalidating specific category subsets.

🚀 Quick Setup & Registration

1. Update Core Configurations (appsettings.json)

{
  "MongoDb": {
    "ConnectionString": "mongodb://username:password@localhost:27017/?replicaSet=rs0",
    "DatabaseName": "CorporateFintechDb",
    "DefaultTransactionTimeout": "00:00:05",
    "SystemCollections": {
      "Outbox": "System_Outbox",
      "AuditLogs": "System_AuditLogs"
    }
  }
}

2. Bootstrap Dependencies (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// 1. Register core Mongo connections, transaction handlers, open-generic repositories, and channel eviction queues
builder.Services.AddMongoDbRepositoryCore(builder.Configuration.GetSection("MongoDb"));

// 2. Scans specific domain assemblies, provisions Time-Series collections, and attaches index verification workers
builder.Services.AddAutomatedIndexes(typeof(CreditFacilityIndexProvider).Assembly);

3. Initialize Mappings on Boot

var app = builder.Build();

// Run domain class profiles and DateOnly/TimeOnly serializers safely
app.Services.InitializeMongoMappings();

app.Run();

🛠 Core Coding Blueprints

1. Creating Time-Series & Auditable Entities

using System;
using MongoDB.Bson;
using MongoDbRepository.Attributes;
using MongoDbRepository.Core.Models;
using MongoDbRepository.Interfaces;

namespace CorporateLending.Domain.Models;

[BsonTimeSeries(TimeField = nameof(Timestamp), MetaField = nameof(SensorId))]
public class TelemetryMetric : BaseDocument<ObjectId>, ITimeSeriesEntity, IAuditableEntity
{
    public DateTime Timestamp { get; set; }
    public string SensorId { get; set; } = string.Empty;
    public double Value { get; set; }
    public DateOnly ReadingDate { get; set; }
    public TimeOnly ReadingTime { get; set; }

    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
}

2. Hybrid AI Search ($rankFusion)

public class AIPortfolioSearchService(ISemanticSearchRepository<InvestmentProfile, string> searchRepo)
{
    public async Task<IReadOnlyList<InvestmentProfile>> SearchPortfoliosAsync(
        string userQuery, 
        ReadOnlyMemory<float> queryEmbedding, 
        CancellationToken cancellationToken)
    {
        var options = new HybridSearchOptions(
            textFieldPath: "OverviewText",
            vectorFieldPath: "Embedding",
            vectorDefinition: new VectorFieldDefinition(1536, VectorSimilarityMetric.Cosine, "portfolio_vector_idx"));

        return await searchRepo.SearchHybridAsync(userQuery, queryEmbedding, options, limit: 10, cancellationToken: cancellationToken);
    }
}

🔒 Automated Testing & Mockless Verification

[Fact]
public async Task CalculateTotalExposure_ShouldFilterSoftDeletedRecords()
{
    var fakeRepo = new InMemoryRepository<CreditFacility, ObjectId>();
    
    var activeId = ObjectId.GenerateNewId();
    var deletedId = ObjectId.GenerateNewId();

    fakeRepo.Seed([
        new CreditFacility { Id = activeId, ApprovedLimit = 5000000, IsDeleted = false },
        new CreditFacility { Id = deletedId, ApprovedLimit = 2000000, IsDeleted = true }
    ]);

    var service = new ExposureCalculator(fakeRepo);

    decimal totalExposure = await service.GetActiveExposureAsync();

    Assert.Equal(5000000, totalExposure);
}
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 (15)

Showing the top 5 NuGet packages that depend on MongoDbRepositoryCore:

Package Downloads
MongoDbRepository.Extensions.Outbox.MessageBus

Package Description

MongoDbRepository.Extensions.Aspire

Package Description

MongoDbRepository.Extensions.Audit.Cryptography

Package Description

MongoDbRepository.Extensions.DataMesh.Bridge

Package Description

MongoDbRepository.Extensions.Polly.Resiliency

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
6.4.3 1,235 8/14/2026
6.4.2 229 8/7/2026
6.4.0 243 8/5/2026
6.3.2 256 8/1/2026
6.3.1 215 8/1/2026
6.3.0 206 7/24/2026
6.2.0 107 7/24/2026
6.1.6 116 7/19/2026
6.1.4 112 7/14/2026
6.1.3 111 7/14/2026
6.1.2 119 7/5/2026
6.1.1 164 7/1/2026
6.1.0 155 6/30/2026
6.0.17 130 6/29/2026
6.0.16 125 6/26/2026
5.0.4 125 5/14/2026
5.0.3 113 4/30/2026
5.0.2 116 4/25/2026
5.0.1 114 4/23/2026
5.0.0 137 4/21/2026
Loading failed