How can I tell the mongodb server is up?

Question:

How can I tell the mongodb server is up and running from python? I currently use

try:
    con = pymongo.Connection()
except Exception as e:
    ...

Or is there a better way in pymongo functions I can use?

Asked By: Tianyun Ling

||

Answers:

Yes, try/except is a good (pythonic) way to check if the server is up. However, it’s best to catch the specific excpetion (ConnectionFailure):

try:
    con = pymongo.Connection()
except pymongo.errors.ConnectionFailure:
    ...
Answered By: shx2

For new versions of pymongo, from MongoClient docs:

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

You can init MongoClient with serverSelectionTimeoutMS to avoid waiting for 20 seconds or so before code it raises exception:

client = MongoClient(serverSelectionTimeoutMS=500)  # wait 0.5 seconds in server selection
Answered By: BangTheBank

Add the following headers:

from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, OperationFailure

Create the connection with MongoDB from Python:

mongoClient = MongoClient("mongodb://usernameMongo:passwordMongo@localhost:27017/?authMechanism=DEFAULT&authSource=database_name", serverSelectionTimeoutMS=500)

Validations

try:
    if mongoClient.admin.command('ismaster')['ismaster']:
        return "Connected!"
except OperationFailure:
    return ("Database not found.")
except ServerSelectionTimeoutError:
    return ("MongoDB Server is down.")
Answered By: Antonio Moreno
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.