MongoDbService 10.2.0

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

MongoDbService

Release to Nuget NuGet

MongoDbService is an open-source C# class library that provides a wrapper around the official MongoDB.Driver, simplifying MongoDB integration in .NET applications.

Features

  • Connection Tracking: Creates a ConnectionRecord collection that keeps track of compute instances connecting to your MongoDB instance, expiring old records via a TTL index
  • Standardized Configuration: Ensures uniform MongoDB configuration across all your projects
  • Simplified Integration: Abstracts connection management so you can focus on business logic

Requirements

  • .NET 10.0
  • MongoDB instance (local or cloud-based)

Installation

Install the NuGet package:

dotnet add package MongoDbService

Configuration

Add the following to your appsettings.json and update the values to match your MongoDB instance:

"MongoDbSettings": {
  "DatabaseName": "YourDatabaseName",
  "ConnectionString": "mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority",
  "ConnectionRecordRetentionDays": 30
}

Configuration Options:

  • DatabaseName (optional): The name of your MongoDB database. Falls back to Untitled-MongoDbService with a warning if omitted.
  • ConnectionString (required): Your MongoDB connection string. Throws if omitted.
  • ConnectionRecordRetentionDays (optional): How long connection-tracking records are kept, enforced by a TTL index. Defaults to 30. Set to 0 or below to keep them indefinitely.

Usage

Inject MongoService into your classes via dependency injection:

Example: Vehicle Management

1. Define your DTO:

using MongoDB.Bson.Serialization.Attributes;

namespace YourNameSpace
{
    public sealed class Vehicle
    {
        [BsonId]
        public required string Id { get; init; }
        public required string Name { get; set; }
    }
}

2. Create a handler class:

using MongoDB.Driver;
using MongoDbService;

namespace YourNameSpace
{
    public sealed class VehicleHandler
    {
        private readonly IMongoCollection<Vehicle> _vehicleCollection;

        public VehicleHandler(MongoService mongoService)
        {
            _vehicleCollection = mongoService.Database.GetCollection<Vehicle>(
                nameof(Vehicle), 
                new MongoCollectionSettings() 
                { 
                    ReadConcern = ReadConcern.Majority, 
                    WriteConcern = WriteConcern.WMajority 
                });
        }

        public async Task AddVehicle(string vehicleName)
        {
            await _vehicleCollection.InsertOneAsync(
                new Vehicle() 
                { 
                    Id = Guid.NewGuid().ToString(), 
                    Name = vehicleName 
                });
        }

        public async Task<DeleteResult> RemoveVehicle(string vehicleId)
        {
            return await _vehicleCollection.DeleteOneAsync(
                Builders<Vehicle>.Filter.Eq(v => v.Id, vehicleId));
        }
    }
}

Short-lived processes

The connection-tracking write is started in the background so it never delays or breaks startup. In a long-running host there is nothing to do. In a short-lived process — a console app, CLI, or function that exits quickly — the process can terminate before the write lands, so await it before returning:

await mongoService.ConnectionRecorded;

ConnectionRecorded never faults; a failed write is logged as a warning, so it needs no try/catch.

Testing

The project includes integration tests that require a running MongoDB instance.

Running Tests Locally

  1. Ensure MongoDB is running on localhost:27017 (or set the MONGODB_CONNECTION_STRING environment variable)
  2. Run the tests:
dotnet test

CI/CD

The GitHub Actions workflow automatically runs tests against a MongoDB container on every release.

Contributing

We welcome contributions! If you find a bug or have an idea for improvement, please submit an issue or pull request on GitHub.

License

This project is licensed under the GNU General Public License v3.0.


Happy coding! 🚀🌐📚

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 (3)

Showing the top 3 NuGet packages that depend on MongoDbService:

Package Downloads
GeoIpServices

A C# library that provides geolocation information for IP addresses with MongoDB caching. Wraps third-party IP geolocation services (IpStack) to reduce API usage and costs through intelligent caching and session management.

SMSwitch

Package Description

MongoDbTokenManager

Create, store and verify one-time tokens (OTTs) in MongoDB: numeric codes for SMS or GUID tokens for email links, with salted hashing, expiry checks and TTL-based cleanup.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.2.0 38 7/29/2026
10.1.1 92 7/17/2026
10.0.0 378 11/24/2025
6.0.0 248 11/23/2025
5.1.0 345 6/28/2025
5.0.1 484 2/12/2025
5.0.0 451 1/5/2025
4.0.0 584 7/28/2024
3.1.0 885 7/7/2024
3.0.0 197 7/6/2024
2.0.0 213 7/5/2024
1.0.0 234 6/23/2024