Ir al contenido

Get started with the MongoDB integrations

Esta página aún no está disponible en tu idioma.

MongoDB logo

MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. The MongoDB integration enables you to connect to existing MongoDB instances (including MongoDB Atlas) or create new instances from Aspire with the docker.io/library/mongo container image.

In this introduction, you’ll see how to install and use the Aspire MongoDB integrations in a simple configuration. If you already have this knowledge, see MongoDB Hosting integration for full reference details.

To begin, install the Aspire MongoDB Hosting integration in your Aspire AppHost project. This integration allows you to create and manage MongoDB database instances from your Aspire hosting projects:

Aspire CLI — Añadir paquete Aspire.Hosting.MongoDB
aspire add mongodb

La CLI de Aspire es interactiva; asegúrate de seleccionar el resultado adecuado cuando se te pida:

Aspire CLI — Ejemplo de salida
Select an integration to add:
> mongodb (Aspire.Hosting.MongoDB)
> Other results listed as selectable options...

Next, in the AppHost project, create instances of MongoDB server and database resources, then pass the database to the consuming client projects:

Select your programming language to get started
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")
.WaitFor(mongodb)
.WithReference(mongodb);
C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
var exampleProject = builder.AddUvicornApp("api", "./api", "main.app")
.WithExternalHttpEndpoints()
.WaitFor(mongodb)
.WithReference(mongodb);
C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mongo = builder.AddMongoDB("mongo")
.WithLifetime(ContainerLifetime.Persistent);
var mongodb = mongo.AddDatabase("mongodb");
var api = builder.AddNodeApp("api", "./api", scriptPath: "index.js")
.WithExternalHttpEndpoints()
.WaitFor(mongodb)
.WithReference(mongodb);

Now that the hosting integration is ready, the next step is to install and configure the client integration in any projects that need to use it.

In each of these consuming client projects, install the Aspire MongoDB client integration:

.NET CLI — Add Aspire.MongoDB.Driver package
dotnet add package Aspire.MongoDB.Driver

In the Program.cs file of your client-consuming project, call the AddMongoDBClient extension method on any IHostApplicationBuilder to register a IMongoClient for use via the dependency injection container. The method takes a connection name parameter.

C# — Program.cs
builder.AddMongoDBClient(connectionName: "mongodb");

To interact with MongoDB databases in your Python consuming projects, you need to include a MongoDB client library. The official option is pymongo, which is MongoDB’s Python driver. You can install this library using pip:

Terminal window
pip install pymongo

Ensure that you import the MongoClient in code files that interact with the database. You should also import the os module to access environment variables:

Python - Import pymongo
from pymongo import MongoClient
import os

To interact with MongoDB databases in your JavaScript consuming projects, you need to include a MongoDB client library. The official option is mongodb, which is MongoDB’s Node.js driver. You can install this library using npm:

Terminal window
npm install mongodb

Ensure that you import the MongoClient in code files that interact with the database:

JavaScript - Import mongodb
const { MongoClient } = require('mongodb');

In the AppHost, when you used the WithReference method to pass a MongoDB database resource to a consuming client project, Aspire injects several configuration properties that you can use in the consuming project.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called mongodb becomes MONGODB_URI.

Use the GetValue() method to obtain these environment variables in consuming projects:

C# - Obtain configuration properties
string connectionUri = builder.Configuration.GetValue<string>("ConnectionStrings__mongodb");
string host = builder.Configuration.GetValue<string>("MONGODB_HOST");
string databaseName = builder.Configuration.GetValue<string>("MONGODB_DATABASENAME");

Use the os.getenv() method to obtain these environment variables in consuming projects:

Python - Obtain configuration properties
connection_uri = os.getenv("ConnectionStrings__mongodb")
host = os.getenv("MONGODB_HOST")
port = os.getenv("MONGODB_PORT")
username = os.getenv("MONGODB_USERNAME")
password = os.getenv("MONGODB_PASSWORD")
database_name = os.getenv("MONGODB_DATABASENAME")

Use the process.env method to obtain these environment variables in consuming projects:

JavaScript - Obtain configuration properties
const connectionUri = process.env.ConnectionStrings__mongodb;
const host = process.env.MONGODB_HOST;
const port = process.env.MONGODB_PORT;
const username = process.env.MONGODB_USERNAME;
const password = process.env.MONGODB_PASSWORD;
const databaseName = process.env.MONGODB_DATABASENAME;

Now that you’ve added the IMongoClient to the builder in the consuming project, you can use the MongoDB database. Get the IMongoClient instance using dependency injection. For example, to retrieve your client object from an example service, define it as a constructor parameter and ensure the ExampleService class is registered with the dependency injection container:

C# — ExampleService.cs
public class ExampleService(IMongoClient client)
{
// Use MongoDB client...
}

Alternatively, if you defined a MongoDB database resource in your AppHost, you can instead require that the dependency injection container provides an IMongoDatabase instance:

C# — ExampleService.cs
public class ExampleService(IMongoDatabase database)
{
// Use MongoDB database...
}

Having obtained the client or database, you can work with the MongoDB database as you would in any other C# application.

Use the information you have obtained about the MongoDB resource to connect to the database. Here is an example of how to connect using pymongo:

Python - Connect to MongoDB
# Create MongoDB client using connection URI
client = MongoClient(connection_uri)
# Get database
db = client[database_name]
# Verify connection
print(f"Connected to MongoDB database: {database_name}")

Having obtained the client, you can work with the MongoDB database as you would in any other Python application.

Use the information you have obtained about the MongoDB resource to connect to the database. Here is an example of how to connect using the mongodb package:

JavaScript - Connect to MongoDB
// Create MongoDB client using connection URI
const client = new MongoClient(connectionUri);
// Connect to MongoDB
await client.connect();
// Get database
const db = client.db(databaseName);
// Verify connection
console.log(`Connected to MongoDB database: ${databaseName}`);

Having obtained the client, you can work with the MongoDB database as you would in any other JavaScript application.

Now, that you have an Aspire app with MongoDB integrations up and running, you can use the following reference documents to learn how to configure and interact with the MongoDB resources: