I am trying to design a Mongo Db connection class where I am maintaning MongoClient as static.
private static MongoClient client = null;
public static DB connectToMongo() throws Exception {
if (null != client) {
return client.getDB(DBNAME);
}
client = new MongoClient(HOST,PORT);
return client.getDB(DBNAME);
}
My whole web application uses the above method to connect to Mongo as follows:
db = MongoDBConnection.connectToMongo();
collection = db.getCollection("collectionName");
After performing DB operations I never call the close connection for MongoClient. The connection class would always return the same instance of MongoClient which is never closed.The only thing I close is cursors.
- Is it necessary to close the MongoClient every time we query the database? Is my above design valid?
You should definitely not close the MongoClient every time you query the database. The MongoClient maintains a connection pool, which is relatively expensive to set up, so you'll want to re-use the MongoClient instance across the lifetime of your web application.
A couple of other things to point out: