.net driver & multiple database

Hi,
I’m wondering, whats the most appropriate way to enable connection with multiple databases in .net using Mongo Driver?
So far, I’ve done single class, where I initialize MongoClient, and few properties, each for one DB connection, which I initialize like e.g. PaymentsDatabase = DbWrapper(mongoClient.GetDatabase(dbName)).

Is that performance-friendly solution? I couldn’t find anything similar on the web about it.

Hi, @Bartek_N_A,

Welcome to the MongoDB Community Forums. I understand that you’re trying to connect to multiple databases and want to understand best practices.

MongoClient represents a connection to a MongoDB cluster - whether that cluster be a standalone, replica set, or sharded cluster. It is thread-safe and should be created once during application bootstrapping. If you are connecting to multiple MongoDB clusters with different connection strings, you would have one MongoClient instance per cluster.

When you instantiate a MongoClient, there are a variety of comparatively expensive operations that must be performed including DNS resolution (including TXT and SRV lookups if you are using mongodb+srv://), creating connection pools for each cluster member, establishing monitoring connections to each cluster member, etc. Much of this is done in the background, but it is the reason why we recommend creating your MongoClient instance during application bootstrapping and reusing that instance throughout the lifetime of the application.

Database objects are lightweight and can be created as-needed. There is nothing wrong with caching the database object returned from client.GetDatabase("test"), but it is more about convenience than performance. Same is true for collection objects returned from database.GetCollection<T>("coll").

In summary, you should create your MongoClient once and cache it during application bootstrapping. You can create database and collection objects on demand or cache them depending on your needs.

Sincerely,
James

2 Likes

Thank you very much for this answer. Hope it will be helpfull for many people in the future wondering about the same thing!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.