17

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.

3

3 Answers 3

19

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")
Sign up to request clarification or add additional context in comments.

3 Comments

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.
if you're getting pymongo.errors.OperationFailure: user is not allowed to do action [validate] change role to Admin
Doesn't work as expected... 🤨 The OperationFailure exception does not occur.
1

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

1

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

This is incorrect!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.