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.

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

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

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.

Automatic TLS and migration from earlier versions

Section titled “Automatic TLS and migration from earlier versions”

Starting in Aspire 13.6, MongoDB participates in Aspire’s shared certificate configuration during local runs. This applies to ordinary AddMongoDBaddMongoDB resources, not just replica sets. When a certificate is configured and available, normally the ASP.NET Core developer certificate under the default settings, Aspire starts MongoDB with --tlsMode requireTLS and adds tls=true to its generated connection string. Without an available configured certificate, the standalone server uses plaintext.

Existing clients that connected without TLS can stop working after upgrading. Use the complete Aspire-generated connection string, such as the MONGODB_URI environment variable for a database resource named mongodb, rather than rebuilding a URI from Host and Port. The generated URI preserves TLS and other connection options, but clients still need to validate the server certificate.

A successful TLS connection requires both:

  • Certificate trust: The client trusts the server certificate or its issuing certificate authority.
  • Hostname validation: The hostname used to connect matches a name in the server certificate.

A client running directly on the host can connect through the generated localhost endpoint using the developer certificate, provided the client’s runtime trusts that certificate. A client running in a container typically reaches MongoDB by its resource name, such as mongo. That name isn’t covered by the default developer certificate, so trusting the certificate alone doesn’t fix the hostname mismatch.

For container-to-container TLS, configure a server certificate whose subject alternative names cover the actual connection hostnames, and configure the client to trust its issuing authority. C# AppHosts can supply a custom certificate with WithHttpsCertificate; this API isn’t available in TypeScript AppHosts. Alternatively, run the consuming app directly on the host with a trusted localhost certificate, or explicitly choose the local-development opt-out below for a standalone or simple single-member server. Don’t use disabled certificate or hostname validation as a general migration solution.

See Certificate configuration for developer-certificate trust and custom server certificates.

If you need plaintext connections for local development, opt out on the MongoDB resource rather than changing certificate defaults for the whole AppHost:

apphost.mts
import {
function createBuilder(): IDistributedApplicationBuilder

Creates a new distributed application builder

createBuilder
} from './.aspire/modules/aspire.mjs';
const
const builder: IDistributedApplicationBuilder
builder
= await
function createBuilder(): IDistributedApplicationBuilder

Creates a new distributed application builder

createBuilder
();
const
const mongo: MongoDBServerResource
mongo
= await
const builder: IDistributedApplicationBuilder
builder
.
IDistributedApplicationBuilder.addMongoDB(name: string, options?: {
port?: number;
userName?: string | ParameterResource;
password?: string | ParameterResource;
}): MongoDBServerResource (+1 overload)

Adds a MongoDB container resource

addMongoDB
("mongo");
await
const mongo: MongoDBServerResource
mongo
.
ContainerResource.withoutHttpsCertificate(): IResourceWithEnvironment

Disable HTTPS/TLS server certificate configuration for the resource. No HTTPS/TLS termination configuration will be applied.

withoutHttpsCertificate
();
await
const builder: IDistributedApplicationBuilder
builder
.
IDistributedApplicationBuilder.build(): DistributedApplication

Builds the distributed application

build
().
DistributedApplication.run(cancellationToken?: cancellationToken): void

Runs the distributed application

run
();

The certificate API is experimental and reports ASPIRECERTIFICATES001 in C#. This opt-out also works when the server uses the simple single-member replica-set configuration: configure WithReplicaSetwithReplicaSet on the same server. That path doesn’t require TLS.

To accept both plaintext and TLS connections while retaining the server’s certificate configuration, select PreferTls:

apphost.mts
import {
function createBuilder(): IDistributedApplicationBuilder

Creates a new distributed application builder

createBuilder
,
type MongoDBTlsMode = "AllowTls" | "PreferTls" | "RequireTls"
const MongoDBTlsMode: {
readonly AllowTls: "AllowTls";
readonly PreferTls: "PreferTls";
readonly RequireTls: "RequireTls";
}

Enum Aspire.Hosting.MongoDBTlsMode

MongoDBTlsMode
} from './.aspire/modules/aspire.mjs';
const
const builder: IDistributedApplicationBuilder
builder
= await
function createBuilder(): IDistributedApplicationBuilder

Creates a new distributed application builder

createBuilder
();
const
const mongo: MongoDBServerResource
mongo
= await
const builder: IDistributedApplicationBuilder
builder
.
IDistributedApplicationBuilder.addMongoDB(name: string, options?: {
port?: number;
userName?: string | ParameterResource;
password?: string | ParameterResource;
}): MongoDBServerResource (+1 overload)

Adds a MongoDB container resource

addMongoDB
("mongo");
await
const mongo: MongoDBServerResource
mongo
.
MongoDBServerResource.withTlsMode(options?: {
mode?: MongoDBTlsMode;
} | undefined): MongoDBServerResource (+1 overload)

Configures the --tlsMode the MongoDB server is started with when TLS is active.

withTlsMode
({
mode?: MongoDBTlsMode | undefined
mode
:
const MongoDBTlsMode: {
readonly AllowTls: "AllowTls";
readonly PreferTls: "PreferTls";
readonly RequireTls: "RequireTls";
}

Enum Aspire.Hosting.MongoDBTlsMode

MongoDBTlsMode
.
type PreferTls: "PreferTls"
PreferTls
});
await
const builder: IDistributedApplicationBuilder
builder
.
IDistributedApplicationBuilder.build(): DistributedApplication

Builds the distributed application

build
().
DistributedApplication.run(cancellationToken?: cancellationToken): void

Runs the distributed application

run
();

This experimental API controls how the server accepts connections when TLS is active; it doesn’t enable TLS without a certificate. The generated connection string still includes tls=true, so consumers using it still need certificate trust and a matching hostname. PreferTls isn’t equivalent to disabling TLS, and allowing plaintext clients leaves those connections unencrypted.

Set ASPIRE_DEVELOPER_CERTIFICATE_DEFAULT_HTTPS_TERMINATION=false in the AppHost’s environment to disable ambient developer-certificate server defaults globally. This affects other resources as well as MongoDB. Prefer the resource-level opt-out when only MongoDB needs different behavior. The global switch doesn’t remove explicit certificate configuration.

MongoDB configurationLocal TLS behavior
Standalone AddMongoDB / addMongoDBUses automatic TLS when a certificate is configured and available; supports the resource-level opt-out.
Simple WithReplicaSet / withReplicaSet on a serverPreserves the server’s automatic TLS behavior; supports the same opt-out without requiring TLS or split-horizon discovery.
Advanced AddMongoDBReplicaSet(...).WithMember(...)Explicitly configures developer certificates unless a member already has certificate configuration. Requires TLS and Server Name Indication (SNI) for split-horizon discovery; don’t use the no-TLS workaround.

The advanced path is for local multi-member experiments. Disabling ambient defaults doesn’t disable its explicit certificate configuration, and initialization fails if a member has no TLS. Its certificate requirements aren’t a reason to disable validation in application clients.

Automatic developer-certificate configuration applies to local run mode. Published MongoDB containers don’t automatically receive the same certificate configuration; configure production transport security for your deployment separately. Both replica-set paths, keyfile configuration, and explicit MongoDB TLS configuration APIs such as WithTlsModewithTlsMode reject publish mode because their deployment support hasn’t been implemented.

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 WithDataVolumewithDataVolume 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 WithDataBindMountwithDataBindMount 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.

Enable transactions and change streams with a single-member replica set

Section titled “Enable transactions and change streams with a single-member replica set”

MongoDB transactions and change streams require replica-set mode, even for a single server. Call WithReplicaSet (C#) or withReplicaSet (TypeScript) directly on the MongoDBServerResource to configure and initialize a single-member replica set, without creating a separate logical replica-set resource or configuring split-horizon TLS. Continue using AddDatabaseaddDatabase, WithReferencewithReference, and WaitForwaitFor as usual — initialization runs during the resource lifecycle, and readiness waits for both initialization and primary election, so consumers can use transactions and change streams as soon as WaitFor completes.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const mongo = await builder.addMongoDB("mongo");
await mongo.withReplicaSet();
const mongodb = await mongo.addDatabase("mongodb");
await builder.addNodeApp("api", "./api", "index.js")
.withReference(mongodb)
.waitFor(mongodb);
// After adding all resources, run the app...

Omit WithReplicaSet / withReplicaSet when a standalone server is sufficient. Both configurations use the automatic TLS behavior introduced in Aspire 13.6; the simple single-member path doesn’t require TLS and supports the same local-development opt-out.

The replica set’s name is optional and defaults to the server’s Aspire resource name. Pass an explicit name to override it:

apphost.mts
const mongo = await builder.addMongoDB("mongo").withReplicaSet({ name: "app-rs" });

Repeated calls with the same configuration are a no-op, but a conflicting name throws. Consumers use the server’s normal endpoint with directConnection=true and the driver’s default primary read preference — no topology discovery, split-horizon addresses, or fixed host ports are required.

MongoDB requires a keyfile when authentication and replication are both enabled, even with a single member. WithReplicaSet generates a secret keyfile automatically when none is configured. To supply your own keyfile content, configure WithKeyFilewithKeyFile with a secret parameter before calling WithReplicaSet:

apphost.mts
const keyfile = await builder.addParameter("mongo-keyfile", { secret: true });
const mongo = await builder.addMongoDB("mongo")
.withKeyFile(keyfile)
.withReplicaSet();

The parameter supplies the keyfile’s contents, not a host file path. The contents must satisfy MongoDB’s keyfile requirements. Supplying a different keyfile after WithReplicaSet conflicts with the generated keyfile and throws.

When using WithDataVolume or WithDataBindMount to persist data, keep the configured credentials and replica set identity unchanged when reusing existing data — MongoDB only applies initial credentials to an empty data directory. With the default set name, renaming the Aspire resource also changes the set identity. Existing compatible single-member data is reused without forced reconfiguration, but mismatched set names, member addresses, or multi-member data are rejected.

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 WithMongoExpresswithMongoExpress 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();

In Aspire 13.6 or later, add WithReplwithRepl to the MongoDB server resource to enable a REPL command that opens mongosh in the terminal dock.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addMongoDB('mongo').withRepl();
await builder.build().run();

The command is opt-in and available only in run mode while the container is running. It uses the container’s bundled client, so no local MongoDB client is needed. The client connects directly to the server inside its container, including replica set members, and authenticates against admin with the resource’s configured credentials. Credentials are passed through environment variables rather than command-line arguments.

When TLS is enabled, the client uses the configured certificate trust bundle and validates the server certificate for localhost. Custom certificates must cover localhost, and their issuing CA must be trusted through Aspire’s certificate configuration.

Use exit before closing the terminal tab. Closing the tab alone can leave the client running inside the container; stopping the container ends any remaining processes.

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.