-
Notifications
You must be signed in to change notification settings - Fork 0
Multi Database
Aryeh Citron edited this page May 12, 2026
·
2 revisions
MongoDB natively supports multiple databases per client. The in-memory emulator fully supports this:
var client = new InMemoryMongoClient();
var ordersDb = client.GetDatabase("orders");
var analyticsDb = client.GetDatabase("analytics");
var orders = ordersDb.GetCollection<Order>("orders");
var events = analyticsDb.GetCollection<Event>("events");var mongo = InMemoryMongo.Builder()
.AddDatabase("orders", db =>
{
db.AddCollection<Order>("orders");
db.AddCollection<OrderItem>("orderItems");
})
.AddDatabase("analytics", db =>
{
db.AddCollection<Event>("events");
})
.Build();
var ordersCollection = mongo.GetDatabase("orders").GetCollection<Order>("orders");
var eventsCollection = mongo.GetDatabase("analytics").GetCollection<Event>("events");services.UseInMemoryMongoDB(options =>
{
options.DatabaseName = "primaryDb";
options.AddCollection<Order>("orders");
});
// For additional databases, add registrations manually:
services.AddSingleton(sp =>
{
var client = sp.GetRequiredService<IMongoClient>() as InMemoryMongoClient;
return client!.GetDatabase("secondaryDb");
});The $lookup aggregation stage supports cross-database joins using the from parameter with database-qualified collection names, provided both databases exist on the same client.
var client = new InMemoryMongoClient();
client.GetDatabase("db1").GetCollection<BsonDocument>("col1");
client.GetDatabase("db2").GetCollection<BsonDocument>("col2");
// List all databases
var dbs = await client.ListDatabaseNamesAsync();
// Drop a database
await client.DropDatabaseAsync("db2");- Setup Guide — DI patterns
- Features — Complete feature reference
Getting Started
Integration & Dependency Injection
Data Management
Reference
- Feature Comparison
- Features
- Filter & Update Operators
- Aggregation Pipeline
- LINQ Support
- API Reference
Help