SharpMongoRepository 0.0.6

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

SharpMongoRepository

SharpMongoRepository is a lightweight, high-performance MongoDB repository pattern implementation for .NET, designed to simplify CRUD operations, index management, and transactions with clean, fluent APIs.


🚀 Features

  • Full CRUD Support – Sync/Async operations
  • Automatic Index Management – Define indexes via attributes or fluent API
  • LINQ & Lambda Support – Expressive querying
  • Transaction Support – ACID-compliant operations
  • Flexible ID TypesObjectId, Guid, string or custom
  • DI-Friendly – Easy integration with IServiceCollection

📦 Installation

dotnet add package SharpMongoRepository

📝 Usage Examples

1. Configure MongoDB Settings (e.g., appsettings.json)

{
  "MongoSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "Database": "ExampleDb"
  }
}

2. Register Services

// Program.cs
builder.Services.Configure<MongoSettings>(builder.Configuration.GetSection("MongoSettings"));

// Register repository with optional indexes
builder.Services.AddMongoRepository<WeatherForecast, Guid>(
    indexes: new List<MongoIndex<WeatherForecast, Guid>>
    {
        MongoDocument<WeatherForecast, Guid>.CreateAscendingIndex(x => x.Date),
        MongoDocument<WeatherForecast, Guid>.CreateCompoundIndex(
            unique: false,
            MongoDocument<WeatherForecast, Guid>.Field(IndexDirection.Ascending, x => x.Date),
            MongoDocument<WeatherForecast, Guid>.Field(IndexDirection.Descending, x => x.TemperatureC)
        )
    }
);

3. Define a Document Model

[BsonCollection("weatherForecasts")] // MongoDB collection name
public class WeatherForecast : IDocument<Guid>
{
    [BsonId]
    public Guid Id { get; set; } = Guid.NewGuid();
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string? Summary { get; set; }
}

4. Minimal API Endpoints

// GET all
app.MapGet("/weatherforecast", async (IMongoRepository<WeatherForecast, Guid> repo) =>
    Results.Ok(await repo.AllAsync().ToListAsync()));

// GET by ID
app.MapGet("/weatherforecast/{id}", async (Guid id, IMongoRepository<WeatherForecast, Guid> repo) =>
    await repo.FindByIdAsync(id) is { } forecast
        ? Results.Ok(forecast)
        : Results.NotFound());

// POST
app.MapPost("/weatherforecast", async (WeatherForecast forecast, IMongoRepository<WeatherForecast, Guid> repo) =>
{
    await repo.InsertOneAsync(forecast);
    return Results.Created($"/weatherforecast/{forecast.Id}", forecast);
});

// DELETE
app.MapDelete("/weatherforecast/{id}", async (Guid id, IMongoRepository<WeatherForecast, Guid> repo) =>
{
    await repo.DeleteByIdAsync(id);
    return Results.NoContent();
});

5. Advanced Queries

// Filter with projection
var coldDays = repo.FilterBy(
    x => x.TemperatureC < 10,
    x => new { x.Date, x.Summary }
);

// Transaction
await repo.WithTransactionAsync(async session =>
{
    await repo.InsertOneAsync(new WeatherForecast { ... }, session);
    await repo.DeleteManyAsync(x => x.TemperatureC > 30, session);
    return "Operation succeeded";
});

📜 Index Management

Define indexes during registration or dynamically:

// Single field
MongoDocument<WeatherForecast, Guid>.CreateAscendingIndex(x => x.Date, unique: true);

// Compound index
MongoDocument<WeatherForecast, Guid>.CreateCompoundIndex(
    unique: true,
    MongoDocument<WeatherForecast, Guid>.Field(IndexDirection.Ascending, x => x.Date),
    MongoDocument<WeatherForecast, Guid>.Field(IndexDirection.Descending, x => x.Summary)
);

⚠️ Error Handling

Custom exceptions (RepositoryException) are thrown for:

  • Connection failures
  • Invalid operations (e.g., duplicate keys)
  • Timeouts (configurable via MongoRepositoryOptions)
try
{
    await repo.InsertOneAsync(document);
}
catch (RepositoryException ex)
{
    logger.LogError(ex, "MongoDB operation failed");
}

🌟 Why Use This?

  • No Boilerplate: Focus on business logic, not MongoDB driver intricacies.
  • Thread-Safe: Lazy-loaded clients and collections.

License: MIT

Product Compatible and additional computed target framework versions.
.NET 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 was computed.  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
0.0.6 278 6/10/2025
0.0.5 228 5/29/2025
0.0.4 135 5/28/2025
0.0.3 136 5/20/2025
0.0.2 334 5/20/2025