how can I put an exceptional handling for checking whether database is exists or not in mongodb using pymongo.
Thanks.
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).
Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError .
An attempt to access a database that doesn't exist is not considered an error. Instead, the database will be created if it doesn't exist when you first write to it.
So if you need to know whether a database already exists, you need to explicitly check. You can call list_database_names()
on your MongoClient
object to get a list of the existing database names:
client = MongoClient()
dbnames = client.list_database_names()
if 'mydbname' in dbnames:
print "It's there!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With