Skip to content

MongoDB Hosting integration reference

MongoDB logo

To get started with the Aspire MongoDB integrations, follow the Get started with MongoDB integrations guide.

This article includes full details about the Aspire MongoDB Hosting integration, which models MongoDB server and database resources as the MongoDBServerResource and MongoDBDatabaseResource types. To access these types and APIs, you need to install the MongoDB Hosting integration in your AppHost project.

The Aspire MongoDB hosting integration models the MongoDB database server as the following types:

  • MongoDBServerResource
  • MongoDBDatabaseResource

To access these types and APIs for expressing them as resources in your AppHost project, install the 📦 Aspire.Hosting.MongoDB NuGet package:

Aspire CLI — Add Aspire.Hosting.MongoDB package
aspire add mongodb

The Aspire CLI is interactive, be sure to select the appropriate search result when prompted:

Aspire CLI — Example output prompt
Select an integration to add:
> mongodb (Aspire.Hosting.MongoDB)
> Other results listed as selectable options...

In the AppHost project, call AddMongoDB to add and return a MongoDB server resource builder. Chain a call to the returned resource builder to AddDatabase, to add a MongoDB database to the server resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
builder.AddProject<Projects.ExampleProject>()
.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 added to the ExampleProject.

The MongoDB server resource includes default credentials:

  • MONGO_INITDB_ROOT_USERNAME: A value of admin
  • MONGO_INITDB_ROOT_PASSWORD: Random password generated using the default password parameter

The password is stored in the AppHost’s secret store in the Parameters section:

{
"Parameters:mongo-password": "<THE_GENERATED_PASSWORD>"
}

The WithReference method configures a connection in the ExampleProject named "mongodb". For more information, see Container resource lifecycle.

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:

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, password);
var mongodb = mongo.AddDatabase("mongodb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mongodb)
.WaitFor(mongodb);

The username and password parameters are usually specified as user secrets:

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

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:

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>()
.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:

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>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

Add MongoDB server resource with initialization data bind mount

Section titled “Add MongoDB server resource with initialization data bind mount”

To add an initialization folder data bind mount to the MongoDB server resource, call the WithInitBindMount method:

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>()
.WithReference(mongodb)
.WaitFor(mongodb);
// After adding all resources, run the app...

The initialization data bind mount is used to initialize the MongoDB server with data. MongoDB executes the scripts found in this folder, which is useful for loading data into the database.

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:

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>()
.WithReference(mongodb)
.WaitFor(mongodb);

When you debug 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

Additionally, the WithMongoExpress API exposes an optional configureContainer parameter that you use to configure the MongoDB Express container resource.

When you use the WithReference method to pass a MongoDB database resource to a non-.NET application (such as Python or JavaScript), Aspire automatically injects environment variables that describe the connection information.

For example, if you reference a MongoDB database resource named mongodb:

C# — AppHost.cs
var mongo = builder.AddMongoDB("mongo");
var mongodb = mongo.AddDatabase("mongodb");
var pythonApp = builder.AddUvicornApp("api", "./api", "main.app")
.WithReference(mongodb);

The following environment variables are available in the Python application:

  • ConnectionStrings__mongodb - The connection string for the MongoDB database
  • MONGODB_HOST - The hostname of the MongoDB server
  • MONGODB_PORT - The port number
  • MONGODB_USERNAME - The username for authentication
  • MONGODB_PASSWORD - The password for authentication
  • MONGODB_AUTHENTICATIONDATABASE - The authentication database
  • MONGODB_AUTHENTICATIONMECHANISM - The authentication mechanism
  • MONGODB_URI - The full connection URI
  • MONGODB_DATABASENAME - The database name

You can access these environment variables in your application code:

Python example
from pymongo import MongoClient
import os
# Get connection properties
connection_uri = os.getenv("ConnectionStrings__mongodb")
database_name = os.getenv("MONGODB_DATABASENAME")
# Create MongoDB client
client = MongoClient(connection_uri)
# Get database
db = client[database_name]
JavaScript example
const { MongoClient } = require('mongodb');
// Get connection properties
const connectionUri = process.env.ConnectionStrings__mongodb;
const databaseName = process.env.MONGODB_DATABASENAME;
// Create MongoDB client
const client = new MongoClient(connectionUri);
// Connect and get database
await client.connect();
const db = client.db(databaseName);

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.