I am trying to create a Mongo Db connection class where I support 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 entire web application uses the above method to connect to Mongo as follows:
db = MongoDBConnection.connectToMongo(); collection = db.getCollection("collectionName");
After performing operations with the database, I never call a close connection for MongoClient. The join class always returned the same MongoClient instance that never closes. The only thing I close is the cursors.
- Do we need to close MongoClient every time we query the database? Is my project higher?
source share