How to Check If a Specific Collection Exists By Name in Python


In this example we will show how to check if a specific collection exists by name in Python MongoDB.

Source Code

from pymongo import MongoClient

client = MongoClient("localhost", 27017)

db = client["mydatabase"]

collection_list = db.list_collection_names()

if "us_state" in collection_list:
    print("The collection exists.")
else:
    print("The collection doesn't exist.")

Output:

The collection exists.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments