コンテンツにスキップ
Docs Try Aspire
Docs Try

Connect to MongoDB

このコンテンツはまだ日本語訳がありません。

MongoDB logo

This page describes how consuming apps connect to a MongoDB resource that is already modeled in your AppHost. For the AppHost API surface — adding a MongoDB server, databases, Mongo Express, volumes, and more — see MongoDB Hosting integration.

When you reference a MongoDB resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire MongoDB client integration for automatic dependency injection, health checks, and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called mongodb becomes MONGODB_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
AuthenticationDatabaseThe authentication database (when credentials are configured)
AuthenticationMechanismThe authentication mechanism (when credentials are 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 server resource and adds:

Property NameDescription
DatabaseNameThe MongoDB database name

Example:

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

Pick the language your consuming app is written in. Each example assumes your AppHost adds a MongoDB server resource named mongo with a database named mongodb and references it from the consuming app.

For C# apps, the recommended approach is the Aspire MongoDB client integration. It registers an IMongoClient (and optionally an IMongoDatabase) through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

The Aspire.MongoDB.Driver NuGet package depends on the MongoDB.Driver NuGet package. With the release of version 3.0.0 of MongoDB.Driver, a binary breaking change was introduced.

  • Aspire.MongoDB.Driver — depends on MongoDB.Driver 2.x. Install this for projects using the MongoDB .NET driver version 2.
  • Aspire.MongoDB.Driver.v3 — depends on MongoDB.Driver 3.x. Install this for projects using the MongoDB .NET driver version 3.

Install the package that matches your MongoDB.Driver version:

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

or

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

In Program.cs, call AddMongoDBClient on your IHostApplicationBuilder to register an IMongoClient:

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

Resolve the client through dependency injection:

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

When you define a MongoDB database resource in your AppHost, you can instead require an IMongoDatabase instance:

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

To register multiple IMongoDatabase instances with different connection names, use AddKeyedMongoDBClient:

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

Then resolve each instance by key:

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.

The Aspire MongoDB client integration offers multiple ways to provide configuration.

Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddMongoDBClient:

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

The connection string is resolved from the ConnectionStrings section:

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

MongoDB Atlas connection strings are also supported:

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

For more information, see MongoDB: ConnectionString documentation.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MongoDBSettings from appsettings.json (or any other configuration source) by using the Aspire:MongoDB:Driver key:

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

Named configuration is also supported, which allows you to configure multiple instances 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
}
}
}
}
}

Named configuration takes precedence over top-level configuration.

Inline delegates. Pass an Action<MongoDBSettings> delegate to configure settings inline:

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

Configuration options:

NameDescription
ConnectionStringThe connection string of the MongoDB database to connect to
DisableHealthChecksWhether the database health check is disabled
HealthCheckTimeoutThe MongoDB health check timeout in milliseconds (int?)
DisableTracingWhether OpenTelemetry tracing is disabled

Aspire client integrations enable health checks by default. The MongoDB client integration adds:

  • A health check that verifies that a connection can be made and commands can be run against the MongoDB database.
  • Integration with the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire MongoDB client integration automatically configures logging and tracing through OpenTelemetry. Metrics are not currently exposed.

Logging categories:

  • MongoDB[.*]

Tracing activities:

  • MongoDB.Driver.Core.Extensions.DiagnosticSources

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

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and pass it to the 📦 MongoDB.Driver NuGet package directly:

C# — Program.cs
using MongoDB.Driver;
var connectionUri = Environment.GetEnvironmentVariable("MONGODB_URI");
var client = new MongoClient(connectionUri);
var database = client.GetDatabase(
Environment.GetEnvironmentVariable("MONGODB_DATABASENAME"));
// Use database to query MongoDB...