Connect to MongoDB
यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।
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.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called mongodb becomes MONGODB_URI.
MongoDB server
Section titled “MongoDB server”The MongoDB server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the MongoDB server |
Port | The port number the MongoDB server is listening on |
Username | The username for authentication |
Password | The password for authentication |
AuthenticationDatabase | The authentication database (when credentials are configured) |
AuthenticationMechanism | The authentication mechanism (when credentials are configured) |
Uri | The 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-256MongoDB database
Section titled “MongoDB database”The MongoDB database resource inherits all properties from its parent server resource and adds:
| Property Name | Description |
|---|---|
DatabaseName | The MongoDB database name |
Example:
Uri: mongodb://admin:p%40ssw0rd1@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256DatabaseName: mongodbConnect from your app
Section titled “Connect from your app”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.
Install the client integration
Section titled “Install the client integration”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 onMongoDB.Driver2.x. Install this for projects using the MongoDB .NET driver version 2.Aspire.MongoDB.Driver.v3— depends onMongoDB.Driver3.x. Install this for projects using the MongoDB .NET driver version 3.
Install the package that matches your MongoDB.Driver version:
dotnet add package Aspire.MongoDB.Driver#:package Aspire.MongoDB.Driver@*<PackageReference Include="Aspire.MongoDB.Driver" Version="*" />or
dotnet add package Aspire.MongoDB.Driver.v3#:package Aspire.MongoDB.Driver.v3@*<PackageReference Include="Aspire.MongoDB.Driver.v3" Version="*" />Add the MongoDB client
Section titled “Add the MongoDB client”In Program.cs, call AddMongoDBClient on your IHostApplicationBuilder to register an IMongoClient:
builder.AddMongoDBClient(connectionName: "mongodb");Resolve the client through dependency injection:
public class ExampleService(IMongoClient client){ // Use client...}When you define a MongoDB database resource in your AppHost, you can instead require an IMongoDatabase instance:
public class ExampleService(IMongoDatabase database){ // Use database...}Add keyed MongoDB clients
Section titled “Add keyed MongoDB clients”To register multiple IMongoDatabase instances with different connection names, use AddKeyedMongoDBClient:
builder.AddKeyedMongoDBClient(name: "mainDb");builder.AddKeyedMongoDBClient(name: "loggingDb");Then resolve each instance by key:
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.
Configuration
Section titled “Configuration”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:
builder.AddMongoDBClient("mongodb");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "mongodb": "mongodb://server:port/test" }}MongoDB Atlas connection strings are also supported:
{ "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:
{ "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:
{ "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:
builder.AddMongoDBClient( "mongodb", static settings => settings.ConnectionString = "mongodb://server:port/test");Configuration options:
| Name | Description |
|---|---|
ConnectionString | The connection string of the MongoDB database to connect to |
DisableHealthChecks | Whether the database health check is disabled |
HealthCheckTimeout | The MongoDB health check timeout in milliseconds (int?) |
DisableTracing | Whether OpenTelemetry tracing is disabled |
Client integration health checks
Section titled “Client integration health checks”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
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”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.
Read environment variables in C#
Section titled “Read environment variables in C#”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:
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...Use the official MongoDB Go driver:
go get go.mongodb.org/mongo-driver/v2/mongoRead the injected environment variable and connect:
package main
import ( "context" "os" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options")
func main() { // Read the Aspire-injected connection URI connStr := os.Getenv("MONGODB_URI")
client, err := mongo.Connect(options.Client().ApplyURI(connStr)) if err != nil { panic(err) } defer client.Disconnect(context.Background())
db := client.Database(os.Getenv("MONGODB_DATABASENAME")) _ = db}Install the official MongoDB Python driver:
pip install pymongoRead the injected environment variables and connect:
import osfrom pymongo import MongoClient
# Read the Aspire-injected connection URIconnection_uri = os.getenv("ConnectionStrings__mongodb")database_name = os.getenv("MONGODB_DATABASENAME")
client = MongoClient(connection_uri)db = client[database_name]
# Use db to query MongoDB...Install the MongoDB Node.js driver:
npm install mongodbRead the injected environment variables and connect:
import { MongoClient } from 'mongodb';
// Read the Aspire-injected connection URIconst connectionUri = process.env.ConnectionStrings__mongodb!;const databaseName = process.env.MONGODB_DATABASENAME!;
const client = new MongoClient(connectionUri);await client.connect();
const db = client.db(databaseName);
// Use db to query MongoDB...await client.close();Or connect using individual properties:
const client = new MongoClient( `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}` + `@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/` + `?authSource=${process.env.MONGODB_AUTHENTICATIONDATABASE}` + `&authMechanism=${process.env.MONGODB_AUTHENTICATIONMECHANISM}`);await client.connect();