MongoDB integration
MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. The MongoDB integration enables you to connect to existing MongoDB instances (including MongoDB Atlas) or create new instances from Aspire with the docker.io/library/mongo container image.
Hosting integration
Section titled “Hosting integration”The MongoDB server hosting integration models the server as the MongoDBServerResource type and the database as the MongoDBDatabaseResource type. To access these types and APIs, add the 📦 Aspire.Hosting.MongoDB NuGet package in your AppHost project:
aspire add mongodbThe Aspire CLI is interactive, be sure to select the appropriate search result when prompted:
Select an integration to add:
> mongodb (Aspire.Hosting.MongoDB)> Other results listed as selectable options...#:package Aspire.Hosting.MongoDB@*<PackageReference Include="Aspire.Hosting.MongoDB" Version="*" />Add MongoDB server resource and database resource
Section titled “Add MongoDB server resource and database resource”In your AppHost project, call AddMongoDB to add and return a MongoDB server resource builder. Chain a call to the returned resource builder to AddDatabase, to add a MongoDB database resource:
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo") .WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);When Aspire adds a container image to the AppHost, it creates a new MongoDB instance on your local machine. The MongoDB server resource includes default credentials:
MONGO_INITDB_ROOT_USERNAME: A value ofadminMONGO_INITDB_ROOT_PASSWORD: Random password generated using the default password parameter
The password is stored in the AppHost’s secret store in the Parameters section:
{ "Parameters:mongo-password": "<THE_GENERATED_PASSWORD>"}The WithReference method configures a connection in the ExampleProject named mongodb and the WaitFor method instructs the AppHost to not start the dependent service until the mongodb resource is ready.
Add MongoDB server resource with data volume
Section titled “Add MongoDB server resource with data volume”To add a data volume to the MongoDB server resource, call the WithDataVolume method on the MongoDB server resource:
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo") .WithDataVolume();
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);The data volume is used to persist the MongoDB server data outside the lifecycle of its container. The data volume is mounted at the /data/db path in the MongoDB server container and when a name parameter isn’t provided, the name is generated at random. For more information on data volumes and details on why they’re preferred over bind mounts, see Docker docs: Volumes.
Add MongoDB server resource with data bind mount
Section titled “Add MongoDB server resource with data bind mount”To add a data bind mount to the MongoDB server resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo") .WithDataBindMount(@"C:\MongoDB\Data");
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);Data bind mounts rely on the host machine’s filesystem to persist the MongoDB server data across container restarts. For more information on data bind mounts, see Docker docs: Bind mounts.
Add MongoDB server resource with initialization data bind mount
Section titled “Add MongoDB server resource with initialization data bind mount”To add an initialization folder data bind mount to the MongoDB server resource, call the WithInitBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo") .WithInitBindMount(@"C:\MongoDB\Init");
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);The initialization data bind mount is used to initialize the MongoDB server with data. MongoDB executes the scripts found in this folder, which is useful for loading data into the database.
Add MongoDB server resource with parameters
Section titled “Add MongoDB server resource with parameters”When you want to explicitly provide the password used by the container image, you can provide these credentials as parameters:
var builder = DistributedApplication.CreateBuilder(args);
var username = builder.AddParameter("username");var password = builder.AddParameter("password", secret: true);
var mongo = builder.AddMongoDB("mongo", username, password);var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);For more information on providing parameters, see External parameters.
Add MongoDB Express resource
Section titled “Add MongoDB Express resource”MongoDB Express is a web-based MongoDB admin user interface. To add a MongoDB Express resource that corresponds to the docker.io/library/mongo-express container image, call the WithMongoExpress method on the MongoDB server resource:
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo") .WithMongoExpress();
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>() .WithReference(mongodb) .WaitFor(mongodb);The MongoDB Express resource is configured to connect to the MongoDB server resource. The default credentials are:
ME_CONFIG_MONGODB_SERVER: The name assigned to the parentMongoDBServerResourceME_CONFIG_BASICAUTH: A value offalseME_CONFIG_MONGODB_PORT: Assigned from the primary endpoint’s target portME_CONFIG_MONGODB_ADMINUSERNAME: The same username as configured in the parentME_CONFIG_MONGODB_ADMINPASSWORD: The same password as configured in the parent
Additionally, the WithMongoExpress API exposes an optional configureContainer parameter that you use to configure the MongoDB Express container resource.
Connection properties
Section titled “Connection properties”When you reference a MongoDB resource using WithReference, the following connection properties are made available to the consuming project:
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 (available when a password parameter is configured) |
AuthenticationDatabase | The authentication database (available when a password parameter is configured) |
AuthenticationMechanism | The authentication mechanism (available when a password parameter is 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 combines the server properties above and adds the following connection property:
| Property Name | Description |
|---|---|
Database | The MongoDB database name |
Hosting integration health checks
Section titled “Hosting integration health checks”The MongoDB hosting integration automatically adds a health check for the MongoDB server resource. The health check verifies that the MongoDB server resource is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.MongoDb NuGet package.
Client integration
Section titled “Client integration”To get started with the Aspire MongoDB client integration, install the 📦 Aspire.MongoDB.Driver NuGet package:
dotnet add package Aspire.MongoDB.Driver#:package Aspire.MongoDB.Driver@*<PackageReference Include="Aspire.MongoDB.Driver" Version="*" />The MongoDB client integration registers an IMongoClient instance that you can use to interact with the MongoDB server resource. If your AppHost adds MongoDB database resources, the IMongoDatabase instance is also registered.
Add MongoDB client
Section titled “Add MongoDB client”In the Program.cs file of your client-consuming project, call the AddMongoDBClient extension method to register a IMongoClient for use via the dependency injection container:
builder.AddMongoDBClient(connectionName: "mongodb");You can then retrieve the IMongoClient instance using dependency injection:
public class ExampleService(IMongoClient client){ // Use 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.
Add keyed MongoDB client
Section titled “Add keyed MongoDB client”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:
builder.AddKeyedMongoDBClient(name: "mainDb");builder.AddKeyedMongoDBClient(name: "loggingDb");Then you can retrieve the IMongoDatabase instances using dependency injection:
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 MongoDB database integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
Use a connection string
Section titled “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 AddMongoDBClient():
builder.AddMongoDBClient("mongo");The connection string is retrieved from the ConnectionStrings configuration section. Consider the following MongoDB example JSON configuration:
{ "ConnectionStrings": { "mongo": "mongodb://server:port/test" }}Alternatively, consider the following MongoDB Atlas example JSON configuration:
{ "ConnectionStrings": { }}For more information on how to format this connection string, see MongoDB: ConnectionString documentation.
Use configuration providers
Section titled “Use configuration providers”The MongoDB integration supports Microsoft.Extensions.Configuration. It loads the MongoDBSettings from configuration using the Aspire:MongoDB:Driver key. Example appsettings.json:
{ "Aspire": { "MongoDB": { "Driver": { "ConnectionString": "mongodb://server:port/test", "DisableHealthChecks": false, "HealthCheckTimeout": 10000, "DisableTracing": false } } }}Use named configuration
Section titled “Use named configuration”The MongoDB integration supports named configuration, which allows you to configure multiple instances of the same resource type 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 } } } }}In this example, the mongo1 and mongo2 connection names can be used when calling AddMongoDBClient:
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.
Use inline configurations
Section titled “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
Section titled “Configuration options”Here are the configurable options:
| Name | Description |
|---|---|
ConnectionString | The connection string of the MongoDB 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 |
Client integration health checks
Section titled “Client integration health checks”By default, Aspire integrations enable health checks for all services. The MongoDB integration handles the following scenarios:
- 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
/healthHTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic
Observability and telemetry
Section titled “Observability and telemetry”Logging
Section titled “Logging”The MongoDB database integration uses standard .NET logging, and you see log entries from the following categories:
MongoDB[.*]: Any log entries from the MongoDB namespace
Tracing
Section titled “Tracing”The MongoDB database integration emits the following Tracing activities using OpenTelemetry:
MongoDB.Driver.Core.Extensions.DiagnosticSources
Metrics
Section titled “Metrics”The MongoDB database integration doesn’t currently expose any OpenTelemetry metrics.