What is the best practice to keep database and collection instances for MongoDB C# / Java drivers

Hi there,

Can somebody please tell me what is the best practice to keep database and collection instances for MongoDB Java and MongoDB C# drivers? Namely, is it safe to keep database and collection instances as a singleton i.e. to keep a single instance of database and collection during the whole application lifetime? I’ve already learned from the documentation that MongoClient should be singleton since it maintains the pool of connections. But what about database and collection instances? I’ve spent some time trying to research this and I’ve found out there are different opinions about this. Someone tells that it’s okay to keep a single instance of database and collection but someone tells that it’s not.

Thanks!

Regards,
Alexey.

This is about the Java driver. The instances of MongoDB database and collections are Java objects, and they are treated as any other Java objects.

How to manage Java objects within an application? This is about memory management in Java and Garbage Collection (GC). GC is automatic managing of memory space used by objects. GC is in turn controlled by Java Virtual Machine (JVM). The application runs in a JVM which in turn runs on your application or web server.

There are lot of aspects and variables. It is a very general subject. I think you have to look for a specific strategy suitable for your situation - the application design, the programming practices, the JVM, memory, the application server, tuning, monitoring and analysis, etc.