I am using Java with MongoDB. Here I am opening MongoClient in each method. I only need to open it once through out the class and close it once.
public class A
{
public String name()
{
MongoClient mongo = new MongoClient(host, port);
DB db = mongo.getDB(database);
DBCollection coll = db.getCollection(collection);
BasicDBObject doc = new BasicDBObject("john", e.getName())
}
public String age()
{
MongoClient mongo = new MongoClient(host, port);
DB db = mongo.getDB(database);
DBCollection coll = db.getCollection(collection);
BasicDBObject doc = new BasicDBObject("age", e.getAge())
}
}
You can use a Singleton pattern to guarantee only one instance of
MongoClientclass per application. Once you obtain the instance ofMongoClient, you can perform your operations and don't need to explicitly manage operations likeMongoClient.close, as this object manages connection pooling automatically.In your example, you can initialize the
MongoClientin a static variable.