Перейти к содержимому

MongoDB Client integration reference

Это содержимое пока не доступно на вашем языке.

MongoDB logo

To get started with the Aspire MongoDB integrations, follow the Get started with MongoDB integrations guide.

This article includes full details about the Aspire MongoDB Client integration, which allows you to connect to and interact with MongoDB databases from your Aspire consuming projects.

You need a MongoDB server and connection information for accessing the server. To get started with the Aspire MongoDB client integration, install the 📦 Aspire.MongoDB.Driver NuGet package in the client-consuming project, that is, the project for the application that uses the MongoDB client. The MongoDB client integration registers an IMongoClient instance that you can use to interact with MongoDB.

.NET CLI — Add Aspire.MongoDB.Driver package
dotnet add package Aspire.MongoDB.Driver

In the Program.cs file of your client-consuming project, call the AddMongoDBClient extension method on any IHostApplicationBuilder to register a IMongoClient for use via the dependency injection container. The method takes a connection name parameter.

C# — Program.cs
builder.AddMongoDBClient(connectionName: "mongodb");

You can then retrieve the IMongoClient instance using dependency injection. For example, to retrieve the connection from an example service:

C# — ExampleService.cs
public class ExampleService(IMongoClient client)
{
// Use the MongoDB Client...
}

The IMongoClient is used to interact with the MongoDB server resource. When you define a MongoDB database resource in your AppHost, you could instead require that the dependency injection container provides an IMongoDatabase instance:

C# — ExampleService.cs
public class ExampleService(IMongoDatabase database)
{
// Use the MongoDB Database...
}

For more information on dependency injection, see .NET dependency injection.

There might be situations where you want to register multiple IMongoDatabase instances with different connection names. To register keyed MongoDB clients, call the AddKeyedMongoDBClient method:

C# — Program.cs
builder.AddKeyedMongoDBClient(name: "mainDb");
builder.AddKeyedMongoDBClient(name: "loggingDb");

Then you can retrieve the IMongoDatabase instances using dependency injection:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("mainDb")] IMongoDatabase mainDatabase,
[FromKeyedServices("loggingDb")] IMongoDatabase loggingDatabase)
{
// Use databases...
}

For more information on keyed services, see .NET dependency injection: Keyed services.

When you use the WithReference method to pass a MongoDB server or database resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called db1 becomes DB1_URI.

The MongoDB server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the MongoDB server
PortThe port number the MongoDB server is listening on
UsernameThe username for authentication
PasswordThe password for authentication (available when a password parameter is configured)
AuthenticationDatabaseThe authentication database (available when a password parameter is configured)
AuthenticationMechanismThe authentication mechanism (available when a password parameter is configured)
UriThe connection URI, with the format mongodb://{Username}:{Password}@{Host}:{Port}/?authSource={AuthenticationDatabase}&authMechanism={AuthenticationMechanism}

Example connection string:

Uri: mongodb://admin:p%40ssw0rd1@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256

The MongoDB database resource inherits all properties from its parent MongoDBServerResource and adds:

Property NameDescription
DatabaseNameThe MongoDB database name

The Aspire MongoDB client integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.

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

C# — Program.cs
builder.AddMongoDBClient("mongo");

The connection string is retrieved from the ConnectionStrings configuration section. Consider the following MongoDB example JSON configuration:

JSON — appsettings.json
{
"ConnectionStrings": {
"mongo": "mongodb://server:port/test"
}
}

Alternatively, consider the following MongoDB Atlas example JSON configuration:

JSON — appsettings.json
{
"ConnectionStrings": {
"mongo": "mongodb+srv://username:password@server.mongodb.net/"
}
}

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

The MongoDB integration supports Microsoft.Extensions.Configuration 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 is an example of an appsettings.json that configures some of the available options:

JSON — appsettings.json
{
"Aspire": {
"MongoDB": {
"Driver": {
"ConnectionString": "mongodb://server:port/test",
"DisableHealthChecks": false,
"HealthCheckTimeout": 10000,
"DisableTracing": false
}
}
}
}

The MongoDB integration supports named configuration, which allows you to configure multiple instances of the same resource type with different settings:

JSON — appsettings.json
{
"Aspire": {
"MongoDB": {
"Driver": {
"mongo1": {
"ConnectionString": "mongodb://server1:port/test",
"DisableHealthChecks": false,
"HealthCheckTimeout": 10000
},
"mongo2": {
"ConnectionString": "mongodb://server2:port/test",
"DisableTracing": true,
"HealthCheckTimeout": 5000
}
}
}
}
}

In this example, the mongo1 and mongo2 connection names can be used when calling AddMongoDBClient:

C# — Program.cs
builder.AddMongoDBClient("mongo1");
builder.AddMongoDBClient("mongo2");

Named configuration takes precedence over the top-level configuration. If both are provided, the settings from the named configuration override the top-level settings.

You can also pass the Action<MongoDBSettings> delegate to set up some or all the options inline, for example to set the connection string from code:

C# — Program.cs
builder.AddMongoDBClient(
"mongodb",
static settings => settings.ConnectionString = "mongodb://server:port/test");

Here are the configurable options with corresponding default values:

NameDescription
ConnectionStringThe connection string of the MongoDB database to connect to
DisableHealthChecksA boolean value that indicates whether the database health check is disabled or not
HealthCheckTimeoutAn int? value that indicates the MongoDB health check timeout in milliseconds
DisableTracingA boolean value that indicates whether the OpenTelemetry tracing is disabled or not

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

By default, the Aspire MongoDB client integration handles the following:

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

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

The Aspire MongoDB client integration uses the following log categories:

  • MongoDB[.*]

The Aspire MongoDB client integration emits the following tracing activities using OpenTelemetry:

  • MongoDB.Driver.Core.Extensions.DiagnosticSources

The Aspire MongoDB client integration doesn’t currently expose any OpenTelemetry metrics.