PollyMongo 1.0.2

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

PollyMongo

NuGet NuGet Downloads CI License: MIT

Polly v8 resilience pipelines for MongoDB.Driver — wrap Find, InsertOne, UpdateOne, DeleteOne, and other IMongoCollection<T> calls with retry, timeout, circuit-breaker, and more using a single ResilientMongoCollection<T> decorator. Zero changes to your queries.

var resilient = collection.WithPolly(pipeline =>
    pipeline
        .AddRetry(new RetryStrategyOptions
        {
            MaxRetryAttempts = 3,
            Delay = TimeSpan.FromMilliseconds(200),
            ShouldHandle = new PredicateBuilder().Handle<MongoException>(),
        })
        .AddTimeout(TimeSpan.FromSeconds(5)));

var orders = await resilient.FindAsync(Builders<Order>.Filter.Eq(o => o.CustomerId, id));

Every MongoDB operation is now automatically wrapped with retry + timeout — zero changes to existing queries.


Why PollyMongo?

MongoDB.Driver has no built-in retry or timeout interception beyond connection-level settings. PollyMongo adds operation-level resilience cleanly.

Without PollyMongo With PollyMongo
Write try/catch + retry loops around every query One WithPolly(...) call
Manually cancel long-running operations Timeout managed by the pipeline
Duplicate retry logic across repositories Single pipeline applied everywhere
Must touch every operation to add resilience Zero changes to existing queries

Installation

dotnet add package PollyMongo

Targets net6.0, net8.0, and net9.0.

Dependencies: Polly.Core 8.*, MongoDB.Driver 3.*, Microsoft.Extensions.DependencyInjection.Abstractions 8.*


Quick start

1. Inline pipeline (ad-hoc usage)

using PollyMongo;

var resilient = collection.WithPolly(pipeline =>
    pipeline.AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        Delay = TimeSpan.FromMilliseconds(200),
        BackoffType = DelayBackoffType.Exponential,
        ShouldHandle = new PredicateBuilder().Handle<MongoException>(),
    }));

var users = await resilient.FindAsync(Builders<User>.Filter.Empty);

2. Pre-built pipeline

var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
    .AddTimeout(TimeSpan.FromSeconds(10))
    .Build();

var resilient = collection.WithPolly(pipeline);
var count = await resilient.CountDocumentsAsync(Builders<Order>.Filter.Empty);

3. Dependency injection

// Program.cs
builder.Services.AddPollyMongo(pipeline =>
    pipeline
        .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
        .AddTimeout(TimeSpan.FromSeconds(5)));

// Repository
public class OrderRepository(IMongoCollection<Order> collection, ResiliencePipeline pipeline)
{
    public Task<List<Order>> GetAllAsync() =>
        collection.WithPolly(pipeline).FindAsync(Builders<Order>.Filter.Empty);

    public Task InsertAsync(Order order) =>
        collection.WithPolly(pipeline).InsertOneAsync(order);
}

Supported operations

Method Description
FindAsync<T> Returns List<T> matching the filter
FindOneAsync<T> First matching document or default
InsertOneAsync Insert a single document
InsertManyAsync Insert multiple documents
UpdateOneAsync Update first matching document
UpdateManyAsync Update all matching documents
ReplaceOneAsync Replace first matching document
DeleteOneAsync Delete first matching document
DeleteManyAsync Delete all matching documents
CountDocumentsAsync Count matching documents
FindOneAndUpdateAsync Atomic find + update
FindOneAndDeleteAsync Atomic find + delete
FindOneAndReplaceAsync Atomic find + replace

Pipeline order

Polly strategies are applied outer-to-inner (left-to-right). The recommended order is:

[Timeout] → [Retry] → [Circuit Breaker] → [MongoDB]
pipeline
    .AddTimeout(TimeSpan.FromSeconds(10))    // 1. Overall deadline
    .AddRetry(retryOptions)                  // 2. Retry on failure
    .AddCircuitBreaker(cbOptions)            // 3. Open circuit if overloaded

ASP.NET Core example

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IMongoClient>(_ =>
    new MongoClient(builder.Configuration.GetConnectionString("Mongo")));

builder.Services.AddScoped(sp =>
    sp.GetRequiredService<IMongoClient>()
      .GetDatabase("mydb")
      .GetCollection<Order>("orders"));

builder.Services.AddPollyMongo(pipeline =>
    pipeline
        .AddRetry(new RetryStrategyOptions
        {
            MaxRetryAttempts = 3,
            Delay = TimeSpan.FromMilliseconds(100),
            BackoffType = DelayBackoffType.Exponential,
            ShouldHandle = new PredicateBuilder()
                .Handle<MongoConnectionException>()
                .Handle<MongoConnectionPoolWaitQueueFullException>()
                .Handle<MongoExecutionTimeoutException>(),
        })
        .AddTimeout(TimeSpan.FromSeconds(30))
        .AddCircuitBreaker(new CircuitBreakerStrategyOptions
        {
            FailureRatio = 0.5,
            MinimumThroughput = 10,
            SamplingDuration = TimeSpan.FromSeconds(30),
            BreakDuration = TimeSpan.FromSeconds(15),
        }));

Package Downloads Description
PollyHealthChecks Downloads ASP.NET Core health checks for Polly v8 circuit breakers — expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses
PollyBackoff Downloads Backoff delay strategies for Polly v8 resilience pipelines
PollyEFCore Downloads Polly v8 resilience pipelines for Entity Framework Core — wrap every EF Core query and SaveChanges with retry, timeout and circuit-breaker via a single AddPollyResilience() call
PollyMailKit Downloads Polly v8 resilience pipelines for MailKit — retry, timeout, and circuit-breaker for SmtpClient.SendAsync and any MailKit SMTP operation
PollyMassTransit Downloads Polly v8 resilience pipelines for MassTransit — retry, timeout, and circuit-breaker for IBus.Publish and ISendEndpointProvider.Send
PollyOpenAI Downloads Polly v8 resilience for OpenAI and Azure OpenAI API calls
PollyAzureEventHub Downloads Polly v8 resilience pipelines for Azure Event Hubs — retry, timeout, and circuit-breaker for EventHubProducerClient and EventHubConsumerClient
PollyElasticsearch Downloads Polly v8 resilience pipelines for Elastic.Clients.Elasticsearch 8+ — retry, timeout, and circuit-breaker for any Elasticsearch operation, plus a built-in ElasticTransientErrors predicate covering rate limiting (429), service unavailability (503), gateway timeouts (504), and connection failures
PollyHangfire Downloads Polly v8 resilience pipelines for Hangfire — retry, timeout, and circuit-breaker for IBackgroundJobClient.Enqueue and Schedule
PollyCosmosDb Downloads Polly v8 resilience pipelines for Azure Cosmos DB — retry, timeout, and circuit-breaker for Container operations, plus a built-in CosmosTransientErrors predicate covering rate limiting (429), timeouts (408), partition failovers (410), and service unavailability (503)
PollySendGrid Downloads Polly v8 resilience pipelines for SendGrid — retry, timeout, and circuit-breaker for ISendGridClient.SendEmailAsync
PollyDapper Downloads Polly v8 resilience pipelines for Dapper — wrap QueryAsync, ExecuteAsync, and other Dapper calls with retry, timeout, circuit-breaker, and more using a single ResilientDbConnection decorator
PollyMediatR Downloads Polly v8 resilience pipelines for MediatR — add retry, timeout, circuit-breaker, rate-limiting, hedging, and chaos engineering to any MediatR request handler with a single line of DI registration
PollySqlClient Downloads Polly v8 resilience pipelines for Microsoft.Data.SqlClient (SQL Server and Azure SQL) — retry, timeout, and circuit-breaker for SqlConnection queries and commands, plus a built-in SqlServerTransientErrors predicate covering all common SQL Server and Azure SQL transient error numbers
PollyAzureKeyVault Downloads Polly v8 resilience pipelines for Azure Key Vault — retry, timeout, and circuit-breaker for SecretClient, KeyClient, and CertificateClient
PollyAzureQueueStorage Downloads Polly v8 resilience pipelines for Azure Queue Storage — retry, timeout, and circuit-breaker for Azure.Storage.Queues QueueClient
PollyRedis Downloads Polly v8 resilience for StackExchange.Redis
PollyAzureServiceBus Downloads Polly v8 resilience for Azure Service Bus — retry, circuit breaker, and timeout for sending and receiving messages
PollyAzureTableStorage Downloads Polly v8 resilience pipelines for Azure Table Storage — retry, timeout, and circuit-breaker for Azure.Data.Tables TableClient
PollyChaos Downloads Chaos engineering and fault-injection resilience strategies for Polly v8 pipelines

💼 Need .NET consulting?

The author of this package is available for consulting on Polly v8 resilience, Azure cloud architecture, and clean .NET design.

→ solidqualitysolutions.com · LinkedIn

License

MIT

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 was computed.  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
1.0.2 239 8/7/2026
1.0.1 139 7/7/2026
1.0.0 141 6/24/2026

1.0.1: Fix package icon (was showing an incorrect/placeholder image). 1.0.0: Initial release. ResilientMongoCollection wraps IMongoCollection calls in a Polly v8 ResiliencePipeline. Supports net6.0, net8.0, and net9.0.