MongoDB Hosting integration reference
Este conteúdo não está disponível em sua língua ainda.
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.
Installation
Section titled “Installation”The Aspire MongoDB hosting integration models the MongoDB database server as the following types:
MongoDBServerResourceMongoDBDatabaseResource
To access these types and APIs for expressing them as resources in your AppHost project, install the 📦 Aspire.Hosting.MongoDB NuGet package:
aspire add mongodbA CLI Aspire é interativa; escolhe o resultado apropriado quando solicitado:
Select an integration to add:
> mongodb (Aspire.Hosting.MongoDB)> Other results listed as selectable options...#:package Aspire.Hosting.MongoDB@*<PackageReference Include="Aspire.Hosting.MongoDB" Version="*" />Add MongoDB server and database resources
Section titled “Add MongoDB server and database resources”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:
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 ofadminMONGO_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:
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:
{ "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:
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:
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:
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.
Create a MongoDB Express resource
Section titled “Create a MongoDB Express resource”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:
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 parentMongoDBServerResourceME_CONFIG_BASICAUTH: A value offalseME_CONFIG_MONGODB_PORT: Assigned from the primary endpoint’s target portME_CONFIG_MONGODB_ADMINUSERNAME: The same username as configured in the parentME_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.
Using with non-.NET applications
Section titled “Using with non-.NET applications”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:
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 databaseMONGODB_HOST- The hostname of the MongoDB serverMONGODB_PORT- The port numberMONGODB_USERNAME- The username for authenticationMONGODB_PASSWORD- The password for authenticationMONGODB_AUTHENTICATIONDATABASE- The authentication databaseMONGODB_AUTHENTICATIONMECHANISM- The authentication mechanismMONGODB_URI- The full connection URIMONGODB_DATABASENAME- The database name
You can access these environment variables in your application code:
from pymongo import MongoClientimport os
# Get connection propertiesconnection_uri = os.getenv("ConnectionStrings__mongodb")database_name = os.getenv("MONGODB_DATABASENAME")
# Create MongoDB clientclient = MongoClient(connection_uri)
# Get databasedb = client[database_name]const { MongoClient } = require('mongodb');
// Get connection propertiesconst connectionUri = process.env.ConnectionStrings__mongodb;const databaseName = process.env.MONGODB_DATABASENAME;
// Create MongoDB clientconst client = new MongoClient(connectionUri);
// Connect and get databaseawait client.connect();const db = client.db(databaseName);Hosting integration health checks
Section titled “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 NuGet package.