AnointedAutomation.Repository.Mongo
1.1.2
See the version list below for details.
dotnet add package AnointedAutomation.Repository.Mongo --version 1.1.2
NuGet\Install-Package AnointedAutomation.Repository.Mongo -Version 1.1.2
<PackageReference Include="AnointedAutomation.Repository.Mongo" Version="1.1.2" />
<PackageVersion Include="AnointedAutomation.Repository.Mongo" Version="1.1.2" />
<PackageReference Include="AnointedAutomation.Repository.Mongo" />
paket add AnointedAutomation.Repository.Mongo --version 1.1.2
#r "nuget: AnointedAutomation.Repository.Mongo, 1.1.2"
#:package AnointedAutomation.Repository.Mongo@1.1.2
#addin nuget:?package=AnointedAutomation.Repository.Mongo&version=1.1.2
#tool nuget:?package=AnointedAutomation.Repository.Mongo&version=1.1.2
AnointedAutomation.Repository.Mongo
A thin, testable wrapper over the official MongoDB .NET driver. IMongoHelper gives you collection name based CRUD, paging, projection, aggregation and index management; MongoRepository<TDoc> is a base class for per collection repositories; and the BSON helpers register class maps and casing conventions for the AnointedAutomation.Objects models.
Installation
dotnet add package AnointedAutomation.Repository.Mongo
- Target framework:
net10.0 - Dependencies:
- AnointedAutomation.Logging
- AnointedAutomation.Objects
- MongoDB.Driver 3.11.2
- MongoDB.Bson 3.11.2
- MongoDB.Libmongocrypt 1.12.0
- Newtonsoft.Json 13.0.4
Quick start
A document type, a repository and DI registration (the IServiceCollection extension assumes an ASP.NET Core or Generic Host app):
using System;
using System.Threading.Tasks;
using AnointedAutomation.Repository.Mongo;
using Microsoft.Extensions.DependencyInjection;
public class Product : MongoDocument
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductRepository : MongoRepository<Product>
{
public ProductRepository(IMongoHelper mongo) : base(mongo, "products") { }
public Task<Product> GetByNameAsync(string name) => GetSingleAsync(p => p.Name == name);
}
public static class MongoSetup
{
public static IServiceCollection AddMongo(this IServiceCollection services, string connectionString)
{
// Once, at startup, before any Mongo call.
BsonClassMapRegistrar.RegisterClassMaps();
services.AddSingleton<IMongoHelperFactory, MongoHelperFactory>();
services.AddSingleton<IMongoHelper>(sp =>
sp.GetRequiredService<IMongoHelperFactory>().Create("shop", connectionString));
services.AddSingleton<ProductRepository>();
return services;
}
}
API overview
All types are in the AnointedAutomation.Repository.Mongo namespace.
Connecting
| Member | Description |
|---|---|
new MongoHelper(string dbName, string connectionString) |
Connects and sets database. (Does not set dbName.) |
IMongoHelperFactory.Create(string dbName, string connectionString) |
MongoHelperFactory returns one cached IMongoHelper per connection string and database, with database and dbName set. |
MongoHelper.ConnectionStringBuilder(username, password, cluster, region) |
Builds mongodb+srv://user:pass@{cluster}.{region}.mongodb.net/?retryWrites=true&w=majority, URL encoding the password. |
MongoHelper.MongoHelperConnector(IMongoHelper, dbName, username, password, cluster, region) |
Builds the connection string, connects, tests the connection and sets dbName. |
IMongoHelper.TestConnection() |
Returns the collection names, or null (and logs an error) if the connection fails. |
IMongoHelper operations
Every method takes the collection name as its first argument.
| Area | Methods |
|---|---|
| Create | CreateDocumentAsync, CreateManyAsync |
| Read | GetByIdAsync, GetSingleAsync, GetFilteredDocumentsAsync, GetAllDocumentsAsync, GetAllDocumentIdsAsync, GetPagedAsync, GetProjectedAsync, DistinctAsync, AggregateAsync, CountAsync, ExistsAsync |
| Update | UpdateDocumentAsync, UpdateManyAsync, UpdateByIdAsync, UpsertAsync, ReplaceDocumentAsync, ReplaceByIdAsync, FindOneAndUpdateAsync |
| Delete | DeleteDocumentAsync (one), DeleteManyAsync, DeleteByIdAsync, FindOneAndDeleteAsync |
| Indexes | EnsureIndexAsync(string, MongoIndexSpec), EnsureIndexesAsync(string, IEnumerable<MongoIndexSpec>) |
- Filters are
FilterDefinition<T>.GetSingleAsync,GetFilteredDocumentsAsync,DeleteDocumentAsync,CountAsyncandExistsAsyncalso accept anExpression<Func<T, bool>>. - The
...ByIdAsyncmethods treat a 24 character hex id as anObjectIdand any other string as a plain string_id. GetAllDocumentsAsyncloads the whole collection; preferGetPagedAsync,CountAsyncorAggregateAsyncfor large collections.
Repository base
| Type | Description |
|---|---|
MongoRepository<TDoc> |
Abstract base with constructor (IMongoHelper mongo, string collectionName) and protected Mongo / CollectionName. Public methods: GetByIdAsync, GetSingleAsync, GetFilteredAsync, GetAllAsync, GetPagedAsync, CountAsync, ExistsAsync, CreateAsync, UpsertAsync, ReplaceByIdAsync, UpdateByIdAsync, DeleteByIdAsync, DeleteManyAsync. |
MongoDocument |
Abstract base with string Id mapped as [BsonId] / ObjectId, and [BsonIgnoreExtraElements]. |
AuditableMongoDocument |
Adds DateTime createdAt and updatedAt. You set these yourself. |
Indexes
| Type | Description |
|---|---|
MongoIndexSpec |
(string field, bool descending = false, bool unique = false, TimeSpan? expireAfter = null, string name = null) or (IReadOnlyList<MongoIndexKey> keys, ...) for compound indexes. ResolveName() gives a deterministic name, so ensuring the same spec repeatedly is idempotent. |
MongoIndexKey |
(string field, bool descending = false). |
BSON and serialization
| Type | Description |
|---|---|
BsonClassMapRegistrar.RegisterClassMaps() |
Idempotent, thread safe. Registers JObjectSerializer for every Newtonsoft JObject and maps AnointedAutomation.Objects.Account.User with UserId as _id and extra elements ignored. |
BsonClassMapRegistrar.RegisterDerivedUser<T>() |
Registers a class derived from User. Call after RegisterClassMaps(). |
BsonClassMapRegistrar.RegisterHybridCasingConvention(string namespacePrefix = "AnointedAutomation") |
Opt in. Registers HybridElementNameConvention for types under the prefix. |
BsonClassMapRegistrar.RegisterSnakeCasingConvention(string namespacePrefix = "AnointedAutomation") |
Opt in. Registers SnakeCaseElementNameConvention (for example LineItems becomes line_items). |
HybridElementNameConvention |
Value type, enum and struct members become camelCase, reference type members PascalCase. Matches JsonCasingConvention in AnointedAutomation.Objects.API. |
SnakeCaseElementNameConvention |
snake_case element names; static string ToSnake(string) is public. |
JObjectSerializer |
BSON serializer for Newtonsoft JObject. |
BsonMap |
ToPlain(BsonValue) and ToDictionary(BsonDocument) convert BSON into plain dictionaries, lists and CLR scalars (ObjectId becomes its hex string). |
Casing conventions
Both conventions are opt in, so installing or upgrading the package changes nothing on its own. Register one once at startup, before RegisterClassMaps() and before any Mongo call, and only after your stored data uses the matching key casing:
using AnointedAutomation.Repository.Mongo;
BsonClassMapRegistrar.RegisterHybridCasingConvention("MyCompany.MyApi");
BsonClassMapRegistrar.RegisterClassMaps();
An explicit [BsonElement("...")] always wins over a convention. Names that are not just a casing variant of the member name (_id, snake_case external fields, deliberate renames) are left alone.
Indexes example
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AnointedAutomation.Repository.Mongo;
public static class Indexes
{
public static Task EnsureAsync(IMongoHelper mongo) =>
mongo.EnsureIndexesAsync("sessions", new List<MongoIndexSpec>
{
new MongoIndexSpec("Email", unique: true),
new MongoIndexSpec("createdAt", expireAfter: TimeSpan.FromDays(1)),
new MongoIndexSpec(new List<MongoIndexKey>
{
new MongoIndexKey("UserId"),
new MongoIndexKey("createdAt", descending: true)
})
});
}
Logging
MongoHelper keeps a static buffer of LogMessage entries (for example connection failures):
using System;
using AnointedAutomation.Optimization.Logging;
using AnointedAutomation.Repository.Mongo;
MongoHelper.LogAdded += (sender, e) => Console.WriteLine(e.log.message);
foreach (LogMessage log in MongoHelper.GetLogs())
{
Console.WriteLine($"[{log.messageType}] {log.message}");
}
MongoHelper.ClearLogs(); // raises LogCleared
Related packages
- AnointedAutomation.Objects: the models
BsonClassMapRegistrarmaps. - AnointedAutomation.Logging: the
LogMessagetype used for the log buffer. - AnointedAutomation.Objects.API: the matching JSON casing convention.
- AnointedAutomation.Repository.MySql: the same repository style for MySQL.
License
MIT. See LICENSE.
Support This Project
This library is free and open source. The best way to support the work is to shop with us:
- Christian items: https://store.anointed.company
- Everything else: https://www.mart.club
Found a bug or have a request? Open an issue at https://github.com/AnointedAutomation/AnointedAutomation/issues.
| 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
- AnointedAutomation.Logging (>= 1.0.3)
- AnointedAutomation.Objects (>= 2.1.3)
- MongoDB.Bson (>= 3.12.0)
- MongoDB.Driver (>= 3.12.0)
- MongoDB.Libmongocrypt (>= 1.12.0)
- Newtonsoft.Json (>= 13.0.4)
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 |
|---|---|---|
| 1.3.2 | 93 | 10/26/2026 |
| 1.3.1 | 508 | 10/1/2026 |
| 1.3.0 | 129 | 10/1/2026 |
| 1.2.2 | 191 | 9/27/2026 |
| 1.2.1 | 105 | 9/27/2026 |
| 1.2.0 | 105 | 9/27/2026 |
| 1.1.2 | 192 | 9/25/2026 |
| 1.1.1 | 453 | 8/23/2026 |
| 1.1.0 | 150 | 8/18/2026 |
| 1.0.6 | 252 | 7/28/2026 |
| 1.0.5 | 189 | 7/26/2026 |
| 1.0.4 | 344 | 6/30/2026 |
| 1.0.3 | 287 | 6/27/2026 |
| 1.0.2 | 352 | 6/24/2026 |
| 1.0.1 | 402 | 5/30/2026 |
| 1.0.0 | 757 | 3/15/2026 |
| 0.0.14 | 206 | 3/14/2026 |
| 0.0.13 | 186 | 3/13/2026 |
| 0.0.12 | 169 | 3/11/2026 |
| 0.0.11 | 460 | 2/25/2026 |