How do you check if the client for a MongoDB instance is valid?

Solution 1:

The serverSelectionTimeoutMS keyword parameter of pymongo.mongo_client.MongoClient controls how long the driver will try to connect to a server. The default value is 30s.

Set it to a very low value compatible with your typical connection time¹ to immediately report an error. You need to query the DB after that to trigger a connection attempt :

>>> maxSevSelDelay = 1 # Assume 1ms maximum server selection delay
>>> client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
                                 serverSelectionTimeoutMS=maxSevSelDelay)
//                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> client.server_info()

This will raise pymongo.errors.ServerSelectionTimeoutError.

¹ Apparently setting serverSelectionTimeoutMS to 0 might even work in the particular case your server has very low latency (case of a "local" server with very light load for example)


It is up to you to catch that exception and to handle it properly. Something like that:

try:
    client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
                                     serverSelectionTimeoutMS=maxSevSelDelay)
    client.server_info() # force connection on a request as the
                         # connect=True parameter of MongoClient seems
                         # to be useless here 
except pymongo.errors.ServerSelectionTimeoutError as err:
    # do whatever you need
    print(err)

will display:

No servers found yet

Solution 2:

Hi to find out that the connection is established or not you can do that :

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
   # The ismaster command is cheap and does not require auth.
   client.admin.command('ismaster')
except ConnectionFailure:
   print("Server not available")