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.
Asked
Active
Viewed 1.0k times
13
-
4Possible duplicate of [How to check in PyMongo if collection exists and if exists empty (remove all from collection)?](http://stackoverflow.com/questions/9822575/how-to-check-in-pymongo-if-collection-exists-and-if-exists-empty-remove-all-fro) – Alex Dec 09 '15 at 15:53
-
@Alex : Thanks ... that solved my problem :) – POOJA GUPTA Dec 09 '15 at 16:57
-
@Alex : Can you please post this as answer so that I can accept this as final answer? – POOJA GUPTA Dec 09 '15 at 16:57
2 Answers
15
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")

MehmedB
- 1,059
- 1
- 16
- 42
-
1I 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. – Thomas J Aug 18 '22 at 13:44
-
if you're getting `pymongo.errors.OperationFailure: user is not allowed to do action [validate]` change role to `Admin` – Bn.F76 Dec 09 '22 at 00:42
-
Doesn't work as expected... The OperationFailure exception does not occur. – Eduardo Lucio Aug 10 '23 at 19:55
0
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))

Eduardo Lucio
- 1,771
- 2
- 25
- 43