.NET Aspire MongoDB database integration
Includes: Hosting integration and Client integration
MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. The .NET Aspire MongoDB integration enables you to connect to existing MongoDB instances (including MongoDB Atlas) or create new instances from .NET with the docker.io/library/mongo
container image
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 the app host project.
dotnet add package Aspire.Hosting.MongoDB
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add MongoDB server resource and database resource
In your app host 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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
Note
The MongoDB container can be slow to start, so it's best to use a persistent lifetime to avoid unnecessary restarts. For more information, see Container resource lifetime.
When .NET Aspire adds a container image to the app host, as shown in the preceding example with the docker.io/library/mongo
image, it creates a new MongoDB instance on your local machine. A reference to your MongoDB server resource builder (the mongo
variable) is used to add a database. The database is named mongodb
and then added to the ExampleProject
. The MongoDB server resource includes default credentials:
MONGO_INITDB_ROOT_USERNAME
: A value ofadmin
.MONGO_INITDB_ROOT_PASSWORD
: Randompassword
generated using the CreateDefaultPasswordParameter method.
When the app host runs, the password is stored in the app host's secret store. It's added to the Parameters
section, for example:
{
"Parameters:mongo-password": "<THE_GENERATED_PASSWORD>"
}
The name of the parameter is mongo-password
, but really it's just formatting the resource name with a -password
suffix. For more information, see Safe storage of app secrets in development in ASP.NET Core and Add MongoDB server resource with parameters.
The WithReference method configures a connection in the ExampleProject
named mongodb
and the WaitFor instructs the app host to not start the dependant service until the mongodb
resource is ready.
Tip
If you'd rather connect to an existing MongoDB server, call AddConnectionString instead. For more information, see Reference existing resources.
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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
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.
Warning
The password is stored in the data volume. When using a data volume and if the password changes, it will not work until you delete the volume.
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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
Important
Data bind mounts have limited functionality compared to volumes, which offer better performance, portability, and security, making them more suitable for production environments. However, bind mounts allow direct access and modification of files on the host system, ideal for development and testing where real-time changes are needed.
Data bind mounts rely on the host machine's filesystem to persist the MongoDB server data across container restarts. The data bind mount is mounted at the C:\MongoDB\Data
on Windows (or /MongoDB/Data
on Unix) path on the host machine in the MongoDB server container. For more information on data bind mounts, see Docker docs: Bind mounts.
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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
The initialization data bind mount is used to initialize the MongoDB server with data. The initialization data bind mount is mounted at the C:\MongoDB\Init
on Windows (or /MongoDB/Init
on Unix) path on the host machine in the MongoDB server container and maps to the /docker-entrypoint-initdb.d
path in the MongoDB server container. MongoDB executes the scripts found in this folder, which is useful for loading data into the database.
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. Consider the following alternative example:
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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
For more information on providing parameters, see External parameters.
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");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...
Tip
To configure the host port for the MongoExpressContainerResource chain a call to the WithHostPort API and provide the desired port number.
The preceding code adds a MongoDB Express resource that is configured to connect to the MongoDB server resource. The default credentials are:
ME_CONFIG_MONGODB_SERVER
: The name assigned to the parentMongoDBServerResource
, in this case it would bemongo
.ME_CONFIG_BASICAUTH
: A value offalse
.ME_CONFIG_MONGODB_PORT
: Assigned from the primary endpoint's target port of the parentMongoDBServerResource
.ME_CONFIG_MONGODB_ADMINUSERNAME
: The same username as configured in the parentMongoDBServerResource
.ME_CONFIG_MONGODB_ADMINPASSWORD
: The same password as configured in the parentMongoDBServerResource
.
Additionally, the WithMongoExpress
API exposes an optional configureContainer
parameter of type Action<IResourceBuilder<MongoExpressContainerResource>>
that you use to configure the MongoDB Express container resource.
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
To get started with the .NET 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 a IMongoClient instance that you can use to interact with the MongoDB server resource. If your app host adds MongoDB database resources, the IMongoDatabase instance is also registered.
dotnet add package Aspire.MongoDB.Driver
Add MongoDB client
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.
builder.AddMongoDBClient(connectionName: "mongodb");
Tip
The connectionName
parameter must match the name used when adding the MongoDB server resource (or the database resource when provided) in the app host project. In other words, when you call AddDatabase
and provide a name of mongodb
that same name should be used when calling AddMongoDBClient
. For more information, see Add MongoDB server resource and database resource.
You can then retrieve the IMongoClient
instance using dependency injection. For example, to retrieve the client from an example service:
public class ExampleService(IMongoClient client)
{
// Use client...
}
The IMongoClient
is used to interact with the MongoDB server resource. It can be used to create databases that aren't already known to the app host project. When you define a MongoDB database resource in your app host, you could instead require that the dependency injection container provides an IMongoDatabase
instance. For more information on dependency injection, see .NET dependency injection.
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");
Important
When using keyed services, it's expected that your MongoDB resource configured two named databases, one for the mainDb
and one for the loggingDb
.
Then you can retrieve the IMongoDatabase
instances using dependency injection. For example, to retrieve the connection from an example service:
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
The .NET Aspire MongoDB database integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
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 builder.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:password@server.mongodb.net/",
}
}
For more information on how to format this connection string, see MongoDB: ConnectionString documentation.
Use configuration providers
The .NET Aspire MongoDB integration supports Microsoft.Extensions.Configuration. It loads the MongoDBSettings from configuration by using the Aspire:MongoDB:Driver
key. The following snippet is an example of a appsettings.json file that configures some of the options:
{
"Aspire": {
"MongoDB": {
"Driver": {
"ConnectionString": "mongodb://server:port/test",
"DisableHealthChecks": false,
"HealthCheckTimeout": 10000,
"DisableTracing": false
},
}
}
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
Here are the configurable options with corresponding default values:
Name | Description |
---|---|
ConnectionString |
The connection string of the MongoDB database 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. |
Health checks
By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.
By default, the .NET Aspire MongoDB client integration handles the following scenarios:
- Adds a health check when enabled that verifies that a connection can be made commands can be run against the MongoDB database within a certain amount of time.
- Integrates with the
/health
HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic
Observability and telemetry
.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. 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.
Logging
The .NET Aspire 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
The .NET Aspire MongoDB database integration emits the following Tracing activities using OpenTelemetry:
MongoDB.Driver.Core.Extensions.DiagnosticSources
Metrics
The .NET Aspire MongoDB database integration doesn't currently expose any OpenTelemetry metrics.
See also
.NET Aspire