Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check database exists in Mongodb using pymongo

how can I put an exceptional handling for checking whether database is exists or not in mongodb using pymongo.

Thanks.

like image 380
Neo Avatar asked Sep 07 '15 12:09

Neo


People also ask

How do you check if record already exists in MongoDB?

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

How do you check PyMongo?

Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError .


1 Answers

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!"
like image 77
JohnnyHK Avatar answered Sep 23 '22 03:09

JohnnyHK