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

5

17

I wonder, if there is a way to check if mongoDB server is running from java driver for mongoDB?

According to the tutorial, I can do

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

But how to check that I can use these Mongo and DB? I see no isConnected() method in the API.

db.getConnector().isOpen() 

returns true

The only way I found is call db.getDatabaseNames() and catch MongoException.

If there some more civilized approach?

Gelding answered 26/7, 2011 at 15:26 Comment(1)
Follow this solution := #17194768Nonfulfillment
F
11

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.

Faa answered 26/7, 2011 at 19:56 Comment(5)
The problem is that this doesn't look as though it is throwing a checked exception - this case is something that can be handled by the caller.Tuttle
If it's not throwing a checked exception in Java, that may actually be a bug. Have you checked jira.mongodb.org for a ticket?Faa
Perhaps this question has become out of date, because on my current mongo version (2.7.3) I can call mongo.getDB("anynameatall") and it won't throw an exception, even when "connected" to a URL with no Mongo running (e.g. "mongodb://127.0.0.1:12345"). I too am stuck with the uncivilised getDatabaseNames() check.Worsham
@DanielFlower, not sure how the Java MongoDB driver has changed over time, but since I've been using it, Mongo.getDB() has never actually hit the server. The driver doesn't seem to bother connecting until it has to; getDB() is just setting up the driver to prepare for real work.Emmieemmit
This approach is not working anymore. Must do : Mongo mongo = new MongoClient("localhost", 27017); DB test = mongo.getDB("test"); DBCollection coll = test.getCollection("test"); coll.findOne();Solvolysis
A
22

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) {
       ...
 }
Allodial answered 29/5, 2013 at 20:33 Comment(4)
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:Nausea
This is the closest equivalent to the Oracle "select 1 from dual" command fond so far.Gerome
Ruby Equivalent of this would be Mongoid.default_client.command(ping: 1)Fauve
@Benoît Guérout- This method is deprecated in Spring Data Mongo 2.1.6.RELEASECesena
N
12

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) {
  ...
}
Nigro answered 16/7, 2013 at 1:28 Comment(4)
Dude, nothing, including ping command or anything could not help to handle java.net.ConnectException. This works like a charm!Angwantibo
It looks like mongo.getAddress() returns null in case mongo is down, Do you really need these extra steps?Jampack
@amazia No. If you're using the latest version which uses MongoClient instance, mongoClient.getAddress() does not return null. Don't know about the earlier versions. This is actually the most effective method. +1Damar
The class DBTCPConnector returned by getConnector() is deprecated in v2.6 and was removed in Mongo v3.0.Flowing
F
11

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.

Faa answered 26/7, 2011 at 19:56 Comment(5)
The problem is that this doesn't look as though it is throwing a checked exception - this case is something that can be handled by the caller.Tuttle
If it's not throwing a checked exception in Java, that may actually be a bug. Have you checked jira.mongodb.org for a ticket?Faa
Perhaps this question has become out of date, because on my current mongo version (2.7.3) I can call mongo.getDB("anynameatall") and it won't throw an exception, even when "connected" to a URL with no Mongo running (e.g. "mongodb://127.0.0.1:12345"). I too am stuck with the uncivilised getDatabaseNames() check.Worsham
@DanielFlower, not sure how the Java MongoDB driver has changed over time, but since I've been using it, Mongo.getDB() has never actually hit the server. The driver doesn't seem to bother connecting until it has to; getDB() is just setting up the driver to prepare for real work.Emmieemmit
This approach is not working anymore. Must do : Mongo mongo = new MongoClient("localhost", 27017); DB test = mongo.getDB("test"); DBCollection coll = test.getCollection("test"); coll.findOne();Solvolysis
J
3
public boolean keepAlive(Mongo mongo) {
    return mongo.getAddress() != null;
}

This will return null for address if mongo is down. You can look within the implementation of getAddress() to see why it is a good way to check the mongo's status.

I assume you've initialized the mongo parameter properly.

Jampack answered 18/11, 2013 at 11:8 Comment(2)
This does not return null even if MongoDB is down. It simply returns a valid com.mongodb.ServerAddress instance which is initialized with the server address and port we provide while initialize Mongo mongo. Or MongoClient mongo with newer versionDamar
You could try mongo.getAllAddress()Lysine
W
1

I haven't tested this thoroughly (only using a localhost mongo) but it appears to work so far:

public boolean mongoRunningAt(String uri) {
    try {
        Mongo mongo = new Mongo(new MongoURI(uri));
        try {
            Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
            socket.connect(mongo.getAddress().getSocketAddress());
            socket.close();
        } catch (IOException ex) {
            return false;
        }
        mongo.close();
        return true;
    } catch (UnknownHostException e) {
        return false;
    }
}

And the tests I've used:

@Test
public void whenMongoNotAvailableAtSpecificURLThenTheLoaderKnows() {
    assertThat(mongoRunningAt("mongodb://127.0.0.1:12345"), is(false));
}

@Test
public void whenMongoAvailableAtSpecificURLThenTheLoaderKnows() {
    assertThat(mongoRunningAt("mongodb://127.0.0.1:27017"), is(true));
}

It's not exactly using a well defined public API so use at your own risk.

Worsham answered 5/4, 2012 at 13:58 Comment(1)
Doesn't that method have the issue that if the mongos is up but the underlying repset/shards aren't it'll report it's up?Whipple

© 2022 - 2024 — McMap. All rights reserved.