Mongoengine check if connection has been successful
Asked Answered
C

2

6

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.

Ching answered 28/4, 2020 at 20:45 Comment(3)
looking at the connect implementation suggests a ConnectionError 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,Fresh
So do you think there is no official function to test the connection?Ching
It seems from the implementation there is not. All it is using is the default MongoClientFresh
S
0

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.

Schenk answered 28/5 at 22:35 Comment(0)
G
0

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
Gayton answered 4/6 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.