Skip to content
Docs Try Aspire
Docs Try

Set up MongoDB in the AppHost

MongoDB logo

This article is the reference for the Aspire MongoDB Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.mts — that you use to model MongoDB server and database resources in your AppHost project.

If you’re new to the MongoDB integration, start with the Get started with MongoDB integrations guide. For how consuming apps read the connection information this page exposes, see Connect to MongoDB.

To start building an Aspire app that uses MongoDB, install the 📦 Aspire.Hosting.MongoDB NuGet package:

Terminal
aspire add mongodb

Learn more about aspire add in the command reference.

Or, choose a manual installation approach:

C# — AppHost.cs
#:package Aspire.Hosting.MongoDB@*
XML — AppHost.csproj
<PackageReference Include="Aspire.Hosting.MongoDB" Version="*" />

Once you’ve installed the hosting integration in your AppHost project, you can add a MongoDB server resource and then add a database resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
var exampleProject = builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

When Aspire adds a container image to the AppHost, as shown in the preceding example with the docker.io/library/mongo image, it creates a new MongoDB server on your local machine. A reference to your MongoDB resource builder (the mongo variable) is used to add a database. The database is named mongodb and then referenced in the consuming project.

The MongoDB server resource includes default credentials:

  • MONGO_INITDB_ROOT_USERNAME: A value of admin
  • MONGO_INITDB_ROOT_PASSWORD: A randomly generated password stored in the AppHost’s secret store under Parameters:mongo-password

Add MongoDB server resource with parameters

Section titled “Add MongoDB server resource with parameters”

When you want to explicitly provide the username and 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: username, password: password);
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

The username and password parameters are typically provided as user secrets:

JSON — secrets.json
{
"Parameters": {
"username": "admin",
"password": "your-secure-password"
}
}

You can also specify a port:

C# — AppHost.cs
var mongo = builder.AddMongoDB("mongo", port: 27017);

For more information, see External parameters.

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:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithDataVolume()
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
builder.AddProject<Projects.ExampleProject>("apiservice")
.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.

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(source: @"C:\MongoDB\Data")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

Add MongoDB server resource with init files

Section titled “Add MongoDB server resource with init files”

Use initialization files to seed the MongoDB server with data or run scripts at startup. The C# AppHost exposes WithInitBindMount(...), while the TypeScript AppHost exposes withInitFiles(...).

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithInitBindMount(source: @"C:\MongoDB\Init")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

MongoDB executes any JavaScript or shell scripts found in the init folder when the container first starts. This is useful for pre-populating collections or creating indexes.

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()
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

When you run the Aspire solution, you’ll see a MongoDB Express container listed in the resources. Select the resource’s endpoint to open the GUI.

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

To configure the host port for the Mongo Express container, pass a configuration callback:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithMongoExpress(c => c.WithHostPort(8081))
.WithLifetime(ContainerLifetime.Persistent);
// After adding all resources, run the app...

By default, Aspire injects the MongoDB connection information using variable names derived from the resource name (for example, MONGODB_URI, MONGODB_HOST, MONGODB_PORT). If your consuming app expects a different set of environment variable names, pass individual connection properties from the AppHost:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo");
var mongodb = mongo.AddDatabase("mongodb");
var app = builder.AddNodeApp("api", "./api", scriptPath: "index.js")
.WithReference(mongodb)
.WithEnvironment(context =>
{
context.EnvironmentVariables["MONGO_HOST"] = mongo.Resource.PrimaryEndpoint.Property(EndpointProperty.Host);
context.EnvironmentVariables["MONGO_PORT"] = mongo.Resource.PrimaryEndpoint.Property(EndpointProperty.Port);
context.EnvironmentVariables["MONGO_USERNAME"] = mongo.Resource.UserNameReference;
context.EnvironmentVariables["MONGO_PASSWORD"] = mongo.Resource.PasswordParameter;
context.EnvironmentVariables["MONGO_DATABASE"] = mongodb.Resource.DatabaseName;
});
builder.Build().Run();

For the full reference of MongoDB connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to MongoDB.

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.