Skip to content

MongoDB integration

MongoDB logo

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.

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 CLI — Add Aspire.Hosting.MongoDB package
aspire add mongodb

The Aspire CLI is interactive, be sure to select the appropriate search result when prompted:

Aspire CLI — Example output prompt
Select an integration to add:
> mongodb (Aspire.Hosting.MongoDB)
> Other results listed as selectable options...

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:

C# — AppHost.cs
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 of admin
  • MONGO_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:

C# — AppHost.cs
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:

C# — AppHost.cs
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:

C# — AppHost.cs
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:

C# — AppHost.cs
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.

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:

C# — AppHost.cs
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 parent MongoDBServerResource
  • ME_CONFIG_BASICAUTH: A value of false
  • ME_CONFIG_MONGODB_PORT: Assigned from the primary endpoint’s target port
  • ME_CONFIG_MONGODB_ADMINUSERNAME: The same username as configured in the parent
  • ME_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.

When you reference a MongoDB resource using WithReference, the following connection properties are made available to the consuming project:

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 combines the server properties above and adds the following connection property:

Property NameDescription
DatabaseThe MongoDB database name

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.

To get started with the Aspire MongoDB client integration, install the 📦 Aspire.MongoDB.Driver NuGet package:

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

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.

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.

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.

The MongoDB database 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 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": {
"mongo": "mongodb+srv://username:[email protected]/"
}
}

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

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
}
}
}
}

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.

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");

Here are the configurable options:

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. 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 /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

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

The MongoDB database integration emits the following Tracing activities using OpenTelemetry:

  • MongoDB.Driver.Core.Extensions.DiagnosticSources

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

FAQCollaborateCommunityDiscussWatch