MongoDB -Add Health Check In ASP.NET Core API

MongoDB -Add Health Check In ASP.NET Core API

In this article, we shall check how to implement MongoDB -Add Health Check In ASP.NET Core API or MVC applications.

Updated November 2026: a section on the AddMongoDb package, a liveness and readiness section, an FAQ and updated setup and timeout guidance.

Implementing a health check is mandatory in many stages of the application development life cycle. It helps you to keep track of the health of numerous resources, databases, and services that your business application relies on in real-time.

This enables you to quickly troubleshoot and resolve technical or environmental issues.

Health check services and middleware in ASP.Net core allow us to validate APIs by allowing us to create health check routes. It also allows us to validate the health of other resources such as external service connections, external databases, and so on.

Example: Mongo Server database

Today in this article, we will cover below aspects,

These simple and easy-to-use feature lets you check the status of your resources and dependencies.

MongoDB Add Health Check- Getting started

If you already have an API, then please follow below two steps,

Create MongoDB health checks using IHealthCheck interface

Creating MongoDB health checks using the IHealthCheck interface is simple and it is explained in detail with high-level steps.

Step1 – Implement Mongo IHealthCheck interface

Here please implement the IHealthCheck interface and override the CheckHealthAsync method.

Here we are defining MongoHealth check using MongoClient and Mongo Database. We shall use the “ping” command to check the connectivity with the database.

public class MongoHealthCheck : IHealthCheck
    {
        private IMongoDatabase _db { get; set; }
        public MongoClient _mongoClient { get; set; }

        public MongoHealthCheck(IOptions<Mongosettings> configuration)
        {
            _mongoClient = new MongoClient(configuration.Value.Connection);

            _db = _mongoClient.GetDatabase(configuration.Value.DatabaseName);

        }

..

}

 

Let’s now define the CheckHealthAsync which is the IHealthCheck interface method implemented for MongoDB connection.

Below is the implementation of the method,

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
         
            var healthCheckResultHealthy = await CheckMongoDBConnectionAsync();


            if (healthCheckResultHealthy)
            {
                return HealthCheckResult.Healthy("MongoDB health check success");
            }

            return HealthCheckResult.Unhealthy("MongoDB health check failure"); ;
        }

HealthCheckResult lets you return health as Healthy, Degraded, or Unhealthy statuses.

CheckMongoDBConnectionAsync method is defined as below,

 private async Task<bool> CheckMongoDBConnectionAsync()
        {
            try
            {
               await _db.RunCommandAsync((Command<BsonDocument>)"{ping:1}");
            }

            catch (Exception)
            {
                return false;
            }

            return true;
        }

In the above method, for any connection failure, you shall get an exception that can be used to return the failure status of the method.

For more granular control the waited method can be used using Example – Wait(1000) where you can configure, how much time you want to wait before reporting the health status.

Step2 – Register MongoDB health check services

In Program.cs (or Startup.ConfigureServices in older projects) please add the HealthChecks as below,

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.Configure<Mongosettings>(options =>
            {
                options.Connection = Configuration.GetSection("MongoSettings:Connection").Value;
                options.DatabaseName = Configuration.GetSection("MongoSettings:DatabaseName").Value;
            });

            services.AddHealthChecks()
               .AddCheck<MongoHealthCheck>("MongoDBConnectionCheck");
            services.AddScoped<IMongoBookDBContext, MongoBookDBContext>();
        }

Below is a sample Configure method,

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseHealthChecks("/healthcheck");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Let’s execute the route “/health check” and we shall get the Mongo Health check success as below,

Health Check for MongoDB ASP.NET Core

You shall be able to verify Healthy, Degraded, or Unhealthy status accordingly.

Browser window showing the ASP.NET Core health check endpoint at localhost:44368/healthcheck returning the word Healthy, circled in red.

References:

Use the AspNetCore.HealthChecks.MongoDb package instead of writing your own

For a standard connectivity check, install the AspNetCore.HealthChecks.MongoDb NuGet package, register one singleton MongoClient, then call AddHealthChecks().AddMongoDb(). The core health checks API already ships in the ASP.NET Core shared framework, so this package is the only extra install.

How does the package find your MongoDB connection?

Current versions don’t take a connection string. They resolve the MongoClient from dependency injection, so you register it once and the check reuses it. MongoDB advises treating clients as singletons because they are expensive to create.

Note: A singleton is one shared object for the whole app. Think of one office phone line that every employee uses, instead of installing a new line for each call.

Many older tutorials still show an AddMongoDb(connectionString) overload. It won’t match current package versions, so don’t copy it. The Step 1 class above has a similar problem, because it builds a new MongoClient in its constructor.

The extension tries to resolve the concrete MongoClient type first, then falls back to IMongoClient. Registering only the interface can behave differently, so register MongoClient itself.

Should the check list databases or ping one?

Pass a databaseNameFactory such as sp => "mydb" so the check pings that database. Without it, the check lists all database names from the client. Pick the ping: listing needs broader permissions, and pinging a named database is the narrower check.

Which parameters are worth setting?

These AddMongoDb parameters matter most in production:

  • name: defaults to "mongodb". Set it if you register more than one MongoDB check.
  • failureStatus: the status reported when the check fails, for example Degraded instead of Unhealthy.
  • tags: let you filter which checks run on an endpoint, such as a readiness route.
  • timeout: stops a slow MongoDB from stalling the probe. Set it below your orchestrator’s probe timeout.

What should you know about compatibility?

The package depends on MongoDB.Driver 3.0.0 or later and Microsoft.Extensions.Diagnostics.HealthChecks 8.0.11 or later. It is a community library, not maintained or supported by Microsoft. Also plan ahead for servers: the .NET driver 3.9.0 release notes say the next minor release will raise the minimum MongoDB Server version from 4.2 to 4.4.

When should you keep the custom IHealthCheck?

Use the package for a plain ping. Keep your own IHealthCheck when you need Degraded for slow responses or other custom logic. Change Step 1 so it takes IMongoClient from DI instead of creating a client, and pass the CancellationToken to the ping so the probe can be cancelled.

Summary

A health check is critical in multiple aspects and allows you to check the health of various resources, databases, services your application is dependent on. Today in this article, we looked at a simple approach of enabling Health Check for MongoDB ASP.NET Core application.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.



Frequently asked questions

Does AddMongoDb take a connection string or a MongoClient in current versions?

Current versions of AspNetCore.HealthChecks.MongoDb don’t build or cache clients. They resolve a MongoClient from the service provider by default, so you register a singleton MongoClient and call AddHealthChecks().AddMongoDb(). Older tutorials that pass a connection string target earlier package versions. Register the concrete MongoClient type, because the extension looks for it first and only then falls back to IMongoClient.

Which NuGet package do I need for a MongoDB health check in ASP.NET Core?

Add AspNetCore.HealthChecks.MongoDb, which depends on MongoDB.Driver 3.0.0 or later. AddHealthChecks and MapHealthChecks are already in the ASP.NET Core shared framework, so you don’t need a package for those. The MongoDB package is community maintained and isn’t supported by Microsoft. If you’d rather not depend on it, a custom IHealthCheck like the one above does the same job.

How do I set a timeout or Degraded status for a slow MongoDB health check?

Pass the timeout and failureStatus parameters to AddMongoDb. In a custom IHealthCheck, pass the CancellationToken to the ping command and return HealthCheckResult.Degraded when MongoDB responds but slowly. Don’t block with Wait(), because it ties up a thread and ignores cancellation.

Do ASP.NET Core health checks run on a schedule or only when the endpoint is called?

They run only when the endpoint is called. To run them periodically, register a health check publisher. In practice, probes from Kubernetes or a load balancer are what normally trigger them, so the probe interval decides how often MongoDB gets pinged.

Leave a Reply

Your email address will not be published. Required fields are marked *