# Set up MongoDB in the AppHost

<Image
  src={mongodbIcon}
  alt="MongoDB logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

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`](/get-started/app-host/) project.

If you're new to the MongoDB integration, start with the [Get started with MongoDB integrations](/integrations/databases/mongodb/mongodb-get-started/) guide. For how consuming apps read the connection information this page exposes, see [Connect to MongoDB](../mongodb-connect/).

## Installation

To start building an Aspire app that uses MongoDB, install the [📦 Aspire.Hosting.MongoDB](https://www.nuget.org/packages/Aspire.Hosting.MongoDB) NuGet package:

```bash title="Terminal"
aspire add mongodb
```

<LearnMore>
  Learn more about [`aspire add`](/reference/cli/commands/aspire-add/) in the command reference.
</LearnMore>

Or, choose a manual installation approach:

```csharp title="C# — AppHost.cs"
#:package Aspire.Hosting.MongoDB@*
```

```xml title="XML — AppHost.csproj"
<PackageReference Include="Aspire.Hosting.MongoDB" Version="*" />
```

```bash title="Terminal"
aspire add mongodb
```

<LearnMore>
  Learn more about [`aspire add`](/reference/cli/commands/aspire-add/) in the command reference.
</LearnMore>

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

```json title="aspire.config.json" ins={3}
{
  "packages": {
    "Aspire.Hosting.MongoDB": "13.3.0"
  }
}
```

## 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:

```csharp title="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...
```
```typescript title="TypeScript — 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`
**Note:** The MongoDB container can be slow to start, so it's best to use a persistent lifetime to avoid unnecessary restarts. For more information, see [Container resource lifetime](/architecture/resource-model/#built-in-resources-and-lifecycle).
**Tip:** If you'd rather connect to an existing MongoDB server, call `AddConnectionString` instead. For more information, see [Reference existing resources](/get-started/resources/).
**Note:** When you reference a MongoDB resource from the AppHost, Aspire makes several properties available to the consuming project, such as connection URIs, hostnames, and port numbers. For a complete list of these properties and per-language connection examples, see [Connect to MongoDB](../mongodb-connect/).

## 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:

```csharp title="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...
```
```typescript title="TypeScript — 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:

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

You can also specify a port:

```csharp title="C# — AppHost.cs"
var mongo = builder.AddMongoDB("mongo", port: 27017);
```
```typescript title="TypeScript — apphost.mts"
const mongo = await builder.addMongoDB("mongo", { port: 27017 });
```
For more information, see [External parameters](/get-started/resources/).

## Add MongoDB server resource with data volume

To add a data volume to the MongoDB server resource, call the `WithDataVolume` method:

```csharp title="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...
```
```typescript title="TypeScript — 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](#add-mongodb-server-resource-with-data-bind-mount), see [Docker docs: Volumes](https://docs.docker.com/engine/storage/volumes).
**Caution:** The password is stored in the data volume. When using a data volume and if the password changes, it will not work until you delete the volume.
**Danger:** Some database integrations, including the MongoDB integration, can't successfully use data volumes after deployment to Azure Container Apps (ACA). This is because ACA uses Server Message Block (SMB) to connect containers to data volumes, and some systems can't use this connection. In the Aspire Dashboard, a database affected by this issue has a status of **Activating** or **Activation Failed** but is never listed as **Running**.

You can resolve the problem by deploying to a Kubernetes cluster, such as Azure Kubernetes Services (AKS). For more information, see [Deploy your first Aspire app](/get-started/deploy-first-app/).

## Add MongoDB server resource with data bind mount

To add a data bind mount to the MongoDB server resource, call the `WithDataBindMount` method:

```csharp title="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...
```
```typescript title="TypeScript — 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...
```
**Note:** Data [bind mounts](https://docs.docker.com/engine/storage/bind-mounts/) have limited functionality compared to [volumes](https://docs.docker.com/engine/storage/volumes/), which offer better performance, portability, and security, making them more suitable for production environments. However, bind mounts allow direct access and modification of files on the host system, ideal for development and testing where real-time changes are needed.

Data bind mounts rely on the host machine's filesystem to persist the MongoDB server data across container restarts. The data bind mount is mounted at the `C:\MongoDB\Data` on Windows (or `/MongoDB/Data` on Unix) path on the host machine in the MongoDB server container. For more information on data bind mounts, see [Docker docs: Bind mounts](https://docs.docker.com/engine/storage/bind-mounts).

## 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(...)`.

```csharp title="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...
```
```typescript title="TypeScript — 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...
```

:::note
The TypeScript AppHost exposes `withInitFiles(source)` instead of `withInitBindMount(source)`. The `withInitFiles` method copies the specified files into the container's init folder, whereas the C# `WithInitBindMount` performs a host bind mount. The functional outcome — running initialization scripts at container startup — is the same.
:::
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

[MongoDB Express](https://github.com/mongo-express/mongo-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:

```csharp title="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...
```
```typescript title="TypeScript — 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

### Configure the Mongo Express host port

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

```csharp title="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...
```
```typescript title="TypeScript — 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...
```
## 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:

```csharp title="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();
```
```typescript title="TypeScript — 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();
```
## 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](../mongodb-connect/).

## 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](https://www.nuget.org/packages/AspNetCore.HealthChecks.MongoDb) NuGet package.