Zum Inhalt springen
DokumentationAspire ausprobieren
DokumentationAusprobieren

Set up MongoDB in the AppHost

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

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.

This updates your aspire.config.json with the MongoDB hosting integration package:

aspire.config.json
{
"packages": {
"Aspire.Hosting.MongoDB": "13.5.3"
}
}

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:

apphost.mts
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 of admin
  • MONGO_INITDB_ROOT_PASSWORD: A randomly generated password stored in the AppHost’s secret store under Parameters:mongo-password
  • MongoDB container imageDocker Hub
    docker.io/library/mongo:8.3

    Added by AddMongoDB()addMongoDB().

    Source

Tags reflect the latest defaults on the microsoft/aspire main branch, and may be newer than the version pinned by the package you install.

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:

apphost.mts
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:

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

You can also specify a port:

apphost.mts
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:

apphost.mts
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:

apphost.mts
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(...).

apphost.mts
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.

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:

apphost.mts
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 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
  • Mongo Express container imageCompanion · MongoDBDocker Hub
    docker.io/library/mongo-express:1.0

    Added by WithMongoExpress()withMongoExpress().

    Source

Tags reflect the latest defaults on the microsoft/aspire main branch, and may be newer than the version pinned by the package you install.

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

apphost.mts
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...

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:

apphost.mts
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();

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.