Ce contenu n’est pas encore disponible dans votre langue.
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.
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...
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
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.
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.
If you need plaintext connections for local development, opt out on the MongoDB resource rather than changing certificate defaults for the whole AppHost:
var builder =DistributedApplication.CreateBuilder(args);
#pragmawarningdisable ASPIREMONGODB001
var mongo =builder.AddMongoDB("mongo")
.WithTlsMode(MongoDBTlsMode.PreferTls);
#pragmawarningrestore ASPIREMONGODB001
builder.Build().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 configuration
Local TLS behavior
Standalone AddMongoDB / addMongoDB
Uses automatic TLS when a certificate is configured and available; supports the resource-level opt-out.
Simple WithReplicaSet / withReplicaSet on a server
Preserves the server’s automatic TLS behavior; supports the same opt-out without requiring TLS or split-horizon discovery.
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.
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.
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(...).
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
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.
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:
var mongo =builder.AddMongoDB("mongo").WithReplicaSet("app-rs");
#pragmawarningrestore ASPIREMONGODB001
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:
var keyfile =builder.AddParameter("mongo-keyfile", secret:true);
#pragmawarningdisable ASPIREMONGODB001
var mongo =builder.AddMongoDB("mongo")
.WithKeyFile(keyfile.Resource)
.WithReplicaSet();
#pragmawarningrestore ASPIREMONGODB001
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:
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);
builder.AddMongoDB("mongo").WithRepl();
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.
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.