Java MongoDB connection pool

2.5k views Asked by At

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())
    }
}
1

There are 1 answers

0
vortex.alex On BEST ANSWER

You can use a Singleton pattern to guarantee only one instance of MongoClient class per application. Once you obtain the instance of MongoClient, you can perform your operations and don't need to explicitly manage operations like MongoClient.close, as this object manages connection pooling automatically.

In your example, you can initialize the MongoClient in a static variable.