I'd like to check whether my script connected to mongoDB successfully. I am using Python and mongoengine. How can I do that? It looks like the connect() method is not actually connecting to the database: if I give it wrong credentials it doesn't raise an error until I run a query on mongo.
Mongoengine check if connection has been successful
Asked Answered
mongoengine connect gives you a PyMongo MongoClient back. Therefore, the suggestions here: PyMongo MongoClient are applicable.
Here is a simple example using mongoengine connect() to get the MongoClient (with the timeoutms set at 1 sec to see the failure faster)
from mongoengine import connect
client = connect(host="wrong_database", timeoutms=1000)
try:
print(f"Ping Database: {client.admin.command('ping')}")
except Exception as e:
print(f"Error Connecting to database: {e}")
ping will return with {'ok': 1.0} for a successful test.
Look at PyMongo errors ConnectionFailure and ConfigurationError for more specific use cases.
The code snippet below should help you.
from mongoengine import connect
mongo_connection = None
DB_URI='mongodb://mongo_username:[email protected]:27017/?authSource=admin'
DB_NAME='your_db_name'
def get_mongo_connection():
global mongo_connection
if mongo_connection is None:
mongo_connection = connect(db=DB_NAME, host=DB_URI, timeoutms=1000)
try:
print(f"MongoDB connection established successfully. {mongo_connection.admin.command('ping')}")
except Exception as e:
print(f"Error Connecting to database: {e}")
return mongo_connection
© 2022 - 2024 — McMap. All rights reserved.
connect
implementation suggests aConnectionError
is raised if it can not be reached. You can always try listing the collections or another small query and raise later that way if it is not working for you, – FreshMongoClient
– Fresh