Search code examples
mongodbc++11mongo-cxx-driver

Is it possible to check if mongoDB is running from cxx driver?


I am wondering if I am able to check that if mongoDB is running from a Cxx driver. The version I am using is 3.0.1.

I tired to dig into mongocxx::client and mongocxx::v_noabi::collection, but I could not find a function/method that seems to do the job.

If the DB is not running, querying will fail and throws an exception. However, it will be better my application could tell me right away whether mongoDB is running or not, rather than throwing an exception when performing a query.

Thanks.


Solution

  • Because of the nature of distributed systems, there's no guarantee that the network is up, that the database is up, etc from moment to moment. That means that all of your queries and writes need to be prepared for the possibility of failure if the database can't be reached. Since you already ought to be accounting for that, it's better to rely on that rather than a standalone "check if the DB is up" test.

    Think about it this way: you have a race condition between checking "is the database up" and your very next operation. We suggest not racing – just write your application to handle failures.

    If – despite that advice – you really want to do a one-off check, use mongocxx::database::run_command to send an {"ismaster" : 1} command to the admin database.