I want to know whether collections of specific names exists in the MongoDB. How can I achieve this programmatically in Python. On searching about the same, I got to know how to do that from MongoDB shell but nothing useful for doing the same in Python.
You can use the method to retrieve and check if your collection exists or not from the comment given by the @Alex like this:
Method 1:
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
list_of_collections = db.list_collection_names() # Return a list of collections in 'test_db'
print("posts" in list_of_collections) # Check if collection "posts" exists in db (test_db)
Or, you can validate a collection with validate_collection() (documentation) This returns an error (pymongo.errors.OperationFailure) if the collection doesn't exist. With this method, you can also catch that exception and do whatever you want.
Method 2:
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
try:
db.validate_collection("random_collection_name") # Try to validate a collection
except pymongo.errors.OperationFailure: # If the collection doesn't exist
print("This collection doesn't exist")
A more complete approach testing connection, database and collection.
Thanks! 😎
#!/usr/bin/python
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def connect_to_mongodb(conn_str: str, database: str, collection: str):
"""Opens the connection to MongoDB."""
try:
mongo_client: MongoClient = MongoClient(conn_str)
# NOTE: The ismaster command is cheap and does not require auth. Useful to
# test if the connection is valid.
mongo_client.admin.command("ismaster")
# NOTE: Test if the base date is valid.
if database not in mongo_client.list_database_names():
raise PyMongoError("Invalid data base!")
# NOTE: Test if the collection is valid.
if collection not in mongo_client[database].list_collection_names():
raise PyMongoError("Invalid collection!")
except PyMongoError as e:
print("Connection to MongoDB failed. Cause: %s" % (e))
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