Set up MongoDB in the AppHost
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.
Installation
Section titled “Installation”To start building an Aspire app that uses MongoDB, install the 📦 Aspire.Hosting.MongoDB NuGet package:
aspire add mongodbLearn more about aspire add in the command reference.
Or, choose a manual installation approach:
#:package Aspire.Hosting.MongoDB@*<PackageReference Include="Aspire.Hosting.MongoDB" Version="*" />aspire add mongodbLearn more about aspire add in the command reference.
This updates your aspire.config.json with the MongoDB hosting integration package:
{ "packages": { "Aspire.Hosting.MongoDB": "13.3.0" }}Add MongoDB server resource
Section titled “Add MongoDB server resource”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:
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withLifetime("Persistent");
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .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 ofadminMONGO_INITDB_ROOT_PASSWORD: A randomly generated password stored in the AppHost’s secret store underParameters: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:
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const userName = await builder.addParameter("username");const password = await builder.addParameter("password", { secret: true });
const mongo = await builder.addMongoDB("mongo", { userName, password });const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .withReference(mongodb) .waitFor(mongodb);
// After adding all resources, run the app...The username and password parameters are typically provided as user secrets:
{ "Parameters": { "username": "admin", "password": "your-secure-password" }}You can also specify a port:
var mongo = builder.AddMongoDB("mongo", port: 27017);const mongo = await 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:
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withDataVolume();await mongo.withLifetime("Persistent");
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .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:
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withDataBindMount("./mongodb-data");await mongo.withLifetime("Persistent");
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .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(...).
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withInitFiles("./mongodb-init");await mongo.withLifetime("Persistent");
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .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.
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() .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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withMongoExpress();await mongo.withLifetime("Persistent");
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js") .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 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
Configure the Mongo Express host port
Section titled “Configure the Mongo Express host port”To configure the host port for the Mongo Express container, pass a configuration callback:
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...import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");await mongo.withMongoExpress({ configureContainer: async c => { await c.withHostPort(8081); }});await mongo.withLifetime("Persistent");
// After adding all resources, run the app...Pass custom environment variables
Section titled “Pass custom environment variables”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:
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();import { createBuilder, EndpointProperty } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");const mongodb = await mongo.addDatabase("mongodb");const mongoEndpoint = await mongo.getEndpoint("tcp");const mongoHost = await mongoEndpoint.property(EndpointProperty.Host);const mongoPort = await mongoEndpoint.property(EndpointProperty.Port);
await builder.addNodeApp("api", "./api", "index.js") .withReference(mongodb) .withEnvironment("MONGO_HOST", mongoHost) .withEnvironment("MONGO_PORT", mongoPort) .withEnvironment("MONGO_USERNAME", mongo.userNameParameter) .withEnvironment("MONGO_PASSWORD", mongo.passwordParameter) .withEnvironment("MONGO_DATABASE", "mongodb");
await builder.build().run();Connection properties
Section titled “Connection properties”For the full reference of MongoDB connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to MongoDB.
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.