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.
-
4Possible duplicate of How to check in PyMongo if collection exists and if exists empty (remove all from collection)?Alex– Alex2015-12-09 15:53:52 +00:00Commented Dec 9, 2015 at 15:53
-
@Alex : Thanks ... that solved my problem :)POOJA GUPTA– POOJA GUPTA2015-12-09 16:57:06 +00:00Commented Dec 9, 2015 at 16:57
-
@Alex : Can you please post this as answer so that I can accept this as final answer?POOJA GUPTA– POOJA GUPTA2015-12-09 16:57:58 +00:00Commented Dec 9, 2015 at 16:57
Add a comment
|
3 Answers
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")
3 Comments
Thomas J
I really prefer the second Method, especially since it also allows you to see if a collection is actually a collection or a view, since list_collection_names() also returns views.
Bn.F76
if you're getting
pymongo.errors.OperationFailure: user is not allowed to do action [validate] change role to AdminEduardo Lúcio
Doesn't work as expected... 🤨 The OperationFailure exception does not occur.
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))
Comments
You can use this code :
client = MongoClient('mongodb://your_mongo_connection_string')
db = client['your_database_name']
collection = db['collectionName']
if collection.count_documents({}):
*#your code based on fondition*
this will check if there is collection exist
1 Comment
Nam G VU
This is incorrect!