Elephant.Database.MongoDb 2.0.0

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

Nuget downloads NuGet Downloads Workflow License: MIT

About

Provides lightweight, dependency-injectable helpers for working with MongoDB in .NET projects. It includes a configurable MongoContext, a generic CRUD repository (IGenericCrudRepository), optional assembly-based configuration auto-loading, and utilities for listing databases to help standardize data access and speed up development.

Features:

  • MongoDb Configurations (that can optionally be auto-loaded).
    • Configurations may optionally be put in a different assembly or even across multiple assemblies.
  • Generic CRUD repository.
  • Generic MongoContext.
  • List all MongoDb databases.

Installation

Choose one:

Package Manager (Visual Studio GUI)

  1. Right-click your project → "Manage NuGet Packages".
  2. Search for Elephant.Database.MongoDb.
  3. Click "Install".

.NET CLI (Command Line)

dotnet add package Elephant.Database.MongoDb

PackageReference (Project File)

<PackageReference Include="Elephant.Database.MongoDb" Version="x.x.x" />

Package Manager (CLI)

nuget install Elephant.Database.MongoDb

How to Use

MongoDb connection strings explained in short

Explanation:
"mongodb://myUser:myPassword@myServerAddress:myMongoDbPortOnServer/myAuthenticationDatabase"

Example with authenication database:
"mongodb://admin:password123@server-001:27017/authDatabase"

Example without authenication database:
"mongodb://admin:password123@server-001:27017"

NOTE: the default MongoDb port is 27017.

You can easily test connection strings to a working MongoDb using Compass (its official and free).

Create a database POCO/Entity

Example:

using Elephant.Database.MongoDb.Types;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoDbShop.Entities.Shop
{
	/// <summary>
	/// Product.
	/// </summary>
	[BsonIgnoreExtraElements]
	public class Product : BaseId // BaseId requires the "Elephant.Database.MongoDb.Types" NuGet.
	{
		/// <summary>
		/// Name.
		/// </summary>
		[BsonElement("name")]
		public string Name { get; set; } = string.Empty;

		/// <summary>
		/// Quantity in store.
		/// </summary>
		[BsonElement("quantity")]
		public int Quantity { get; set; } = 0;

		/// <summary>
		/// Price per entity.
		/// </summary>
		[BsonElement("price")]
		public decimal Price { get; set; } = 1.25M;

		/// <summary>
		/// Description.
		/// </summary>
		[BsonElement("description")]
		public string Description { get; set; } = string.Empty;
	}
}

Create a custom repository and interface that inherits from the generic one

Example:

// Requires NuGets "Elephant.Database.MongoDb" and "Elephant.Database.MongoDb.Abstractions".

public interface IProductRepository : IGenericCrudRepository<Product>
{
	// Your custom methods here.
}

public class ProductRepository : GenericCrudRepository<Product>, IProductRepository
{
	/// <summary>
	/// Constructor.
	/// </summary>
	public ProductRepository(IShopContext shopContext) : base(shopContext.Products)
	{
        // Your custom methods here. You may use the inherited variable DbSet.
	}
}

(Optional) Add them to the dependency injection

public void ConfigureServices(..)
{
    ..
        
	services.AddMongoContext<IShopContext, ShopContext>(options =>
	{
		options.ConnectionString = "mongodb://myUser:myPassword@myServerAddress:myServerPort/myAuthenticationDatabase" "Your MongoDb connection string here";
		options.DatabaseName = "Your mongoDb Database name here (case sensitive!)";
	});

	services.AddScoped<IProductRepository, ProductRepository>();
	services.AddScoped<IDatabaseRepository, DatabaseRepository>(x => new DatabaseRepository(new MongoClient(Constants.ConnectionString))); // This one is also optional.
}

Conventions

camelCase example

using Elephant.Database.MongoDb;

public void ConfigureServices(IServiceCollection services, ..)
{
    ConfigureDatabases(..)       
    ..
}

public void ConfigureDatabases(IServiceCollection services, ..)
{
   // Execute this BEFORE creating your MongoDb context. So usually before services.AddMongoContext<..>(options => ..);
   ConventionPacks.EnforceGlobalCamelCase(); // Add optional namespaces as needed in the parameter.
   
   // Configure your MongoDB context(s) here somewhere.
}

Upgrade instructions

1.0.0 → 2.0.0

  • MongoContext.AutoLoadConfigurationsByAssemblyNames(..) now may throw an InvalidOperationException instead of an NullReferenceException.
  • MongoContextOptionsBuilder.Configure(..), MongoContextOptionsBuilder.GetCollectionInstance(..), MongoContextOptionsBuilder.Entity(..) may throw InvalidOperationException now instead of a NullReferenceException.
  • Elephant.Database.MongoDb.DbSets.DbSet constructor changed from public DbSet(IMongoContextOptionsBuilder optionsBuilder, IMongoContext context, IMongoCollection<TEntity> collection) into public DbSet(IMongoCollection<TEntity> collection)

Contributing

Contributions are welcome. Please read our CONTRIBUTING.md file for guidelines on how to proceed.

License

This project is licensed under the MIT License. See the LICENSE.txt file for details.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  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
2.0.0 136 12/31/2025
1.2.5 432 11/19/2025
1.2.4 235 3/28/2025
1.2.3 347 11/15/2023
1.2.2 1,764 11/2/2023
1.2.1 212 10/30/2023
1.2.0 388 6/16/2023
1.1.0 318 6/6/2023
1.0.3 268 6/4/2023

AutoLoadConfigurationsByAssemblyNames may throw a different error.