Is there a way to create a set of X connections to mongodb using MongoClient on application startup?

I want to create a “X” number of connections to mongodb on my application startup (i.e before my application starts taking traffic).

MongoDB Version: 4.0.11

Mongo Java Driver Version (maven): 3.4.1

I have tried setting the “minConnectionsPerHost” to the required number, but when i execute the code it barely open 1 or 2 connections. But, when i put load on my application the connection count is slowly going up to accommodate the traffic. I want to create those connections before my application starts taking traffic.

        ServerAddress address = new ServerAddress("localhost", 27017);
        List<ServerAddress> serverAddresses = Arrays.asList(address);

        MongoCredential credential = 
        MongoCredential.createCredential("XXXX", "XXXX", 
        List<MongoCredential> mongoCredentials = 

        MongoClientOptions clientOptions = 
        MongoClient mongoClient = new MongoClient(serverAddresses, 
              mongoCredentials, clientOptions);

Is there a way to achieve this using the mongo java driver?

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You can set a minConnectionsPerHost() in the options builder, and then use a warmup script to create many connections. The connection pool will keep the minConnectionsPerHost connections alive without closing.

The warmup script can have a program which spawns 2*minConnectionsPerHost number of threads, which will connect and do may be a dummy read operation. This way connections will be opened, minimum connections will be kept alive.

This seems to be dirty solution 🙂 But might work!