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?
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:
...
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
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.")
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?
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:
...
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
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.")