MongoDB implementation of RepositoryKit. Implements IRepository, IRepositoryQuery and IRepositoryBulk using MongoClient and IMongoCollection.
$ dotnet add package RepositoryKit.MongoDB
MongoDB Implementation for RepositoryKit
This package provides the MongoDB implementation of RepositoryKit’s abstractions.
It enables consistent, testable, and flexible repository patterns for MongoDB projects —
without unnecessary UnitOfWork or transaction layers.
| Class | Purpose |
|---|---|
MongoReadOnlyRepository<TEntity, TContext> | Read-only LINQ-style queries for MongoDB |
MongoRepository<TEntity, TContext> | Full-featured CRUD repository for MongoDB |
builder.Services.AddSingleton<IMongoClient>(_ => new MongoClient("mongodb://localhost:27017"));
builder.Services.AddScoped<IMongoDatabase>(sp =>
sp.GetRequiredService<IMongoClient>().GetDatabase("SampleDb"));
builder.Services.AddScoped<IProductRepository, ProductRepository>();
app.MapPost("/products", async (IProductRepository repo, Product product) =>
{
await repo.AddAsync(product);
return Results.Created($"/products/{product.Id}", product);
});
public interface IProductRepository : IRepository<Product>
{
Task<List<Product>> GetExpensiveProductsAsync(decimal minPrice);
}
public class ProductRepository : MongoRepository<Product, IMongoDatabase>, IProductRepository
{
public ProductRepository(IMongoDatabase db) : base(db) { }
public async Task<List<Product>> GetExpensiveProductsAsync(decimal minPrice)
{
return await _collection.Find(p => p.Price > minPrice).ToListAsync();
}
}
app.MapGet("/products/expensive", async (IProductRepository repo, decimal minPrice) =>
{
var expensive = await repo.GetExpensiveProductsAsync(minPrice);
return Results.Ok(expensive);
});
All LINQ-based RepositoryKit.Extensions (like Shuffle, FirstOrNone, GroupBySelect, SafeDistinct, etc.)
can be used directly in your MongoDB sample:
var products = await repo.GetAllAsync();
var shuffled = products.Shuffle().ToList();
Repository operations wrap errors with the standard RepositoryException from RepositoryKit.Core:
try
{
await repo.AddAsync(product);
}
catch (RepositoryException ex)
{
// Handle or log error info
}
MIT © Ataberk Kaya
📎 This package is the official MongoDB provider for RepositoryKit.