I am using MongoDB with Java and have some problems and questions about my connection. First of all, how should I connect to Mongo? Should I use a static client and leave it
how should I connect to Mongo?
As it sounds, you're already using MongoClient
, its a good way to go.
The MongoClient
class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.
Should I use a static client and leave it open?
The MongoClient
instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.
Do I need to explicitly close connection?
No, you don't. And that as well should resolve the error that you're getting.
Here is a Quick Tour on making the connection using MongoClient.