how to check from a driver, if mongoDB server is running how to check from a driver, if mongoDB server is running mongodb mongodb

how to check from a driver, if mongoDB server is running


You can run a ping command

 Mongo mongo = new Mongo(); DBObject ping = new BasicDBObject("ping", "1"); try {       mongo.getDB("dbname").command(ping); } catch (MongoException e) {       ... }


I've found this to be more direct than the ping command:

Mongo mongo = new Mongo();try {  mongo.getConnector().getDBPortPool(mongo.getAddress()).get().ensureOpen();} catch (Exception e) {  ...}


if there is a way to check if mongoDB server is running from java driver for MongoDB?

So if you can do the following:

Mongo m = new Mongo( "localhost" , 27017 );DB db = m.getDB( "mydb" );

Then you are connected to the database, otherwise that m.getDB() would be throwing an exception. If you can connect to the database, then the MongoDB server is running.

The only way I found is call db.getDatabaseNames() and catch MongoException. If there some more civilized approach?

Is there something specifically wrong with this approach?

The driver basically runs in a sandbox where it can or cannot connect. You're asking the driver to know something specific about the server (is process X running?), but that's not the driver's job. It can either connect or it can't, it's not responsible for operating the service/process, just for connecting to it.

To know that the process is actually running, you need administrative functions on that server that allow you to check that mongod is indeed running with the correct parameters.