Get started with the MongoDB integrations
Bu içerik henüz dilinizde mevcut değil.
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.
Set up hosting integration
Section titled “Set up hosting integration”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 add mongodbAspire CLI etkileşimlidir; istendiğinde uygun sonucu seçin:
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="*" />Next, in the AppHost project, create instances of MongoDB server and database resources, then pass the database to the consuming client projects:
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);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);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);Use the integration in client projects
Section titled “Use the integration in client projects”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.
Set up client projects
Section titled “Set up client projects”In each of these consuming client projects, install the Aspire MongoDB client integration:
dotnet add package Aspire.MongoDB.Driver#:package Aspire.MongoDB.Driver@*<PackageReference Include="Aspire.MongoDB.Driver" Version="*" />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.
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:
pip install pymongoEnsure that you import the MongoClient in code files that interact with the database. You should also import the os module to access environment variables:
from pymongo import MongoClientimport osTo 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:
npm install mongodbEnsure that you import the MongoClient in code files that interact with the database:
const { MongoClient } = require('mongodb');Use injected MongoDB properties
Section titled “Use injected MongoDB properties”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:
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:
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:
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;Use MongoDB resources in client code
Section titled “Use MongoDB resources in client code”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:
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:
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:
# Create MongoDB client using connection URIclient = MongoClient(connection_uri)
# Get databasedb = client[database_name]
# Verify connectionprint(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:
// Create MongoDB client using connection URIconst client = new MongoClient(connectionUri);
// Connect to MongoDBawait client.connect();
// Get databaseconst db = client.db(databaseName);
// Verify connectionconsole.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.
Next steps
Section titled “Next steps”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: