Skip to content

Multi Database

Aryeh Citron edited this page May 12, 2026 · 2 revisions

Multi-Database

Overview

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");

Builder Pattern

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");

DI Registration

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");
});

Cross-Database Operations

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.

Listing and Dropping Databases

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");

See Also

Clone this wiki locally