I'm looking for best way to check connection to Mongo DB. Situation: client makes request (api) to server. And server returns status of all databases.

What the best way to do it?

Solution 1

I use this:

Builder o = MongoClientOptions.builder().connectTimeout(3000);  
MongoClient mongo = new MongoClient(new ServerAddress("", 3001), o.build());    

try {
} catch (Exception e) {
  System.out.println("Mongo is down");

Solution 2

In Java MongoDriver 3.3.0 use ServerMonitorListener to determine whether server is up and connected or not. Here is the example code,

public class ServerConnection implements ServerMonitorListener {
    private MongoClient client;

    public ServerConnection(){
        try {
            MongoClientOptions clientOptions = new MongoClientOptions.Builder()

            client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions);
        } catch (Exception ex) {


    public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) {
        // Ping Started

    public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) {
        // Ping Succeed, Connected to server

    public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) {
        // Ping failed, server down or connection lost

Solution 3

The ping command is a no-op used to test whether a server is responding to commands. This command will return immediately even if the server is write-locked:


            DBObject ping = new BasicDBObject("ping", "1");
            mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
        } catch (Exception exp){
            // MongoDb is down..

Solution 4

Use MongoClient for Java, all the info you need is here...


Solution 5

If I understand your question correctly you want to get state returned via a web service call. You can write a function that invokes db.serverStatus() and have it return the data. Check out the documentation here:

Monitoring for MongoDB