Overview
The Aspire.MongoDB.Driver component registers an IMongoClient in your dependency injection container for connecting to MongoDB databases. It automatically enables health checks, logging, and distributed tracing.
Installation
Install the component using the .NET CLI:
dotnet add package Aspire.MongoDB.Driver
Usage
Register the component
In your service’s Program.cs file, call the AddMongoDBClient extension method:
builder . AddMongoDBClient ( "mongodb" );
Inject and use the client
Retrieve the IMongoClient instance using dependency injection:
public class ProductsController : ControllerBase
{
private readonly IMongoClient _mongoClient ;
private readonly IMongoDatabase _database ;
private readonly IMongoCollection < Product > _products ;
public ProductsController ( IMongoClient mongoClient )
{
_mongoClient = mongoClient ;
_database = mongoClient . GetDatabase ( "catalog" );
_products = _database . GetCollection < Product >( "products" );
}
[ HttpGet ]
public async Task < IActionResult > GetProducts ()
{
var products = await _products . Find ( _ => true ). ToListAsync ();
return Ok ( products );
}
[ HttpGet ( "{id}" )]
public async Task < IActionResult > GetProduct ( string id )
{
var product = await _products . Find ( p => p . Id == id ). FirstOrDefaultAsync ();
if ( product == null )
{
return NotFound ();
}
return Ok ( product );
}
[ HttpPost ]
public async Task < IActionResult > CreateProduct ( Product product )
{
await _products . InsertOneAsync ( product );
return CreatedAtAction ( nameof ( GetProduct ), new { id = product . Id }, product );
}
}
Configuration
The component provides multiple configuration options based on your project requirements.
Connection string
Provide a connection string in your appsettings.json:
{
"ConnectionStrings" : {
"mongodb" : "mongodb://localhost:27017/catalog"
}
}
Then register the component using the connection name:
builder . AddMongoDBClient ( "mongodb" );
For more information on connection string format, see the MongoDB connection string documentation .
Configuration providers
Configure component settings using the Aspire:MongoDB:Driver configuration section:
{
"Aspire" : {
"MongoDB" : {
"Driver" : {
"ConnectionString" : "mongodb://localhost:27017/catalog" ,
"DisableHealthChecks" : false ,
"HealthCheckTimeout" : 10000 ,
"DisableTracing" : false
}
}
}
}
Inline configuration
Configure settings directly in code using a delegate:
builder . AddMongoDBClient ( "mongodb" , settings =>
{
settings . ConnectionString = "mongodb://localhost:27017/catalog" ;
settings . DisableHealthChecks = false ;
});
AppHost integration
In your AppHost project, install the MongoDB hosting package:
dotnet add package Aspire.Hosting.MongoDB
Register a MongoDB server and database in your AppHost’s Program.cs:
var mongodb = builder . AddMongoDB ( "mongo" )
. AddDatabase ( "catalog" );
var myService = builder . AddProject < Projects . MyService >()
. WithReference ( mongodb );
The WithReference method automatically configures the connection string in your service. Consume it in your service’s Program.cs:
builder . AddMongoDBClient ( "catalog" );
The connection name passed to WithReference must match the name used in AddMongoDBClient.
Configuration options
The following settings are available:
Setting Description Default ConnectionStringMongoDB connection string nullDisableHealthChecksDisable automatic health check registration falseHealthCheckTimeoutHealth check timeout in milliseconds 10000DisableTracingDisable OpenTelemetry tracing false
Health checks
The component automatically registers a health check that verifies the MongoDB connection. The health check:
Connects to the MongoDB server
Executes a ping command
Reports the status in the /health endpoint
You can disable health checks by setting DisableHealthChecks to true.
Observability
Logging
The component integrates with .NET logging to provide:
Connection events
Command execution information
Error details
Tracing
Distributed tracing captures:
Database operations
Query execution time
Connection activity
Traces appear in the Aspire dashboard and integrate with OpenTelemetry collectors.
Common scenarios
CRUD operations
public class ProductService
{
private readonly IMongoCollection < Product > _products ;
public ProductService ( IMongoClient mongoClient )
{
var database = mongoClient . GetDatabase ( "catalog" );
_products = database . GetCollection < Product >( "products" );
}
// Create
public async Task < Product > CreateAsync ( Product product )
{
await _products . InsertOneAsync ( product );
return product ;
}
// Read
public async Task < Product > GetByIdAsync ( string id )
{
return await _products . Find ( p => p . Id == id ). FirstOrDefaultAsync ();
}
// Update
public async Task < bool > UpdateAsync ( string id , Product product )
{
var result = await _products . ReplaceOneAsync ( p => p . Id == id , product );
return result . ModifiedCount > 0 ;
}
// Delete
public async Task < bool > DeleteAsync ( string id )
{
var result = await _products . DeleteOneAsync ( p => p . Id == id );
return result . DeletedCount > 0 ;
}
}
Filtering and querying
public async Task < List < Product >> SearchProductsAsync ( string category , decimal minPrice )
{
var filter = Builders < Product >. Filter . And (
Builders < Product >. Filter . Eq ( p => p . Category , category ),
Builders < Product >. Filter . Gte ( p => p . Price , minPrice )
);
return await _products . Find ( filter )
. Sort ( Builders < Product >. Sort . Ascending ( p => p . Name ))
. Limit ( 100 )
. ToListAsync ();
}
Aggregation pipeline
public async Task < List < CategoryStats >> GetCategoryStatsAsync ()
{
var pipeline = new []
{
new BsonDocument ( "$group" , new BsonDocument
{
{ "_id" , "$category" },
{ "count" , new BsonDocument ( "$sum" , 1 ) },
{ "avgPrice" , new BsonDocument ( "$avg" , "$price" ) }
}),
new BsonDocument ( "$sort" , new BsonDocument ( "count" , - 1 ))
};
return await _products . Aggregate < CategoryStats >( pipeline ). ToListAsync ();
}
Bulk operations
public async Task BulkInsertAsync ( List < Product > products )
{
var bulkOps = products . Select ( p => new InsertOneModel < Product >( p ));
await _products . BulkWriteAsync ( bulkOps );
}
Best practices
Use indexes for better performance
Use projection to reduce data transfer
Only retrieve the fields you need: var projection = Builders < Product >. Projection
. Include ( p => p . Name )
. Include ( p => p . Price )
. Exclude ( p => p . Id );
var products = await _products . Find ( _ => true )
. Project ( projection )
. ToListAsync ();
Handle concurrency with versions
Use version fields for optimistic concurrency: public class Product
{
public string Id { get ; set ; }
public string Name { get ; set ; }
public int Version { get ; set ; }
}
var filter = Builders < Product >. Filter . And (
Builders < Product >. Filter . Eq ( p => p . Id , id ),
Builders < Product >. Filter . Eq ( p => p . Version , currentVersion )
);
var update = Builders < Product >. Update
. Set ( p => p . Name , newName )
. Inc ( p => p . Version , 1 );
var result = await _products . UpdateOneAsync ( filter , update );
if ( result . ModifiedCount == 0 )
{
throw new ConcurrencyException ();
}
The IMongoClient instance manages connection pooling automatically. Reuse the same client instance throughout your application.
Implement retries for transient failures
MongoDB operations may fail due to transient issues. Implement retry logic: var settings = MongoClientSettings . FromConnectionString ( connectionString );
settings . RetryWrites = true ;
settings . RetryReads = true ;
Additional resources
PostgreSQL Connect to PostgreSQL databases
Redis Add caching with Redis
Azure Cosmos DB Connect to Azure Cosmos DB
MongoDB Hosting Learn about the MongoDB hosting integration