close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do you check if the client for a MongoDB instance is valid in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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 :

  2. you check if the client for a MongoDB instance is valid

    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 :

Method 1

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")

Method 2

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read