.NET Aspire MongoDB database component

In this article, you learn how to use the .NET Aspire MongoDB database component. The Aspire.MongoDB.Driver library:

  • Registers a IMongoClient in the DI container for connecting MongoDB database.
  • Automatically configures the following:
    • Health checks, logging and telemetry to improve app monitoring and diagnostics

Prerequisites

  • MongoDB database and connection string for accessing the database.

Get started

To get started with the .NET Aspire MongoDB database component, install the Aspire.MongoDB.Driver NuGet package.

dotnet add package Aspire.MongoDB.Driver

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Example usage

In the Program.cs file of your component-consuming project, call the AddMongoDBClient extension to register a IMongoClient for use via the dependency injection container.

builder.AddMongoDBClient("mongodb");

To retrieve your IMongoClient object, consider the following example service:

public class ExampleService(IMongoClient mongoClient)
{
    // Use mongoClient...
}

After adding a IMongoClient, you can require the IMongoClient instance using DI.

App host usage

To model the MongoDB resource in the app host, install the Aspire.Hosting.MongoDB NuGet package.

dotnet add package Aspire.Hosting.MongoDB

In your app host project, register the MongoDB database and consume the connection method and consume the service using the following methods:

var builder = DistributedApplication.CreateBuilder(args);

var mongo = builder.AddMongoDB("mongo");
var mongodb = mongo.AddDatabase("mongodb");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(mongodb);

Configuration

The .NET Aspire MongoDB database component provides multiple configuration approaches and options to meet the requirements and conventions of your project.

Use a connection string

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling builder.AddMongoDBClient():

builder.AddMongoDBClient("MongoConnection");

And then the connection string will be retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "MongoConnection": "mongodb://server:port/test",
  }
}

For more information on how to format this connection string, see MongoDB: ConnectionString documentation.

Use configuration providers

The .NET Aspire MongoDB database component supports Microsoft.Extensions.Configuration. It loads the MySqlConnectorSettings from configuration files such as appsettings.json by using the Aspire:MongoDB:Driver key. If you have set up your configurations in the Aspire:MongoDB:Driver section, you can just call the method without passing any parameter.

The following example shows an appsettings.json file that configures some of the available options:

{
  "Aspire": {
    "MongoDB": {
      "Driver": {
        "ConnectionString": "mongodb://server:port/test",
        "DisableHealthChecks": false,
        "HealthCheckTimeout": 10000,
        "DisableTracing": false
      },
    }
  }
}

Use inline configurations

You can also pass the Action<MongoDBSettings> delegate to set up some or all the options inline:

builder.AddMongoDBClient("mongodb",
    static settings => settings.ConnectionString = "mongodb://server:port/test");

Configuration options

Here are the configurable options with corresponding default values:

Name Description
ConnectionString The connection string of the MongoDB database database to connect to.
DisableHealthChecks A boolean value that indicates whether the database health check is disabled or not.
HealthCheckTimeout An int? value that indicates the MongoDB health check timeout in milliseconds.
DisableTracing A boolean value that indicates whether the OpenTelemetry tracing is disabled or not.

Health checks

By default, .NET Aspire components enable health checks for all services. For more information, see .NET Aspire components overview.

By default, the .NET Aspire MongoDB database component handles the following:

  • Adds a health check when enabled that verifies that a connection can be made commands can be run against the MongoDB database within a certain amount of time.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

Observability and telemetry

.NET Aspire components automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about component observability and telemetry, see .NET Aspire components overview. Depending on the backing service, some components may only support some of these features. For example, some components support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

The .NET Aspire MongoDB database component uses standard .NET logging, and you'll see log entries from the following categories:

  • MongoDB[.*]: Any log entries from the MongoDB namespace.

Tracing

The .NET Aspire MongoDB database component will emit the following Tracing activities using OpenTelemetry:

  • "MongoDB.Driver.Core.Extensions.DiagnosticSources"

Metrics

The .NET Aspire MongoDB database component doesn't currently expose any OpenTelemetry metrics.

See also