Justin Justin - 1 month ago 31
Java Question

creating a mongodb healthcheck (in dropwizard)

Not necessarily specific to dropwizard, but for the life of me I can't figure out how to easily create a healthcheck for mongodb. This is in java, using version 3.3.0 of mongodb's own java driver.

I was hoping there would be a method that doesn't change the state of the database if it succeeds, but also throws an Exception when the query (or connection, or whatever) fails in order to return a health or unhealthy state. Ideally I'd perform a

find
, but this doesn't throw an Exception as far as I can tell.

Answer

I would just list all collections in database like:

MongoClient client = new MongoClient(addr, opts);
MongoDatabase db = client.getDatabase(database);
try {
    MongoIterable<String> allCollections = db.listCollectionNames();
    for (String collection : allCollections) {
        System.out.println("MongoDB collection: " + collection);
    }
} catch (Exception me) {
    // problems with mongodb
}