SwadhyAI Notes

All Python notes

MongoDB Collection 📚

Creating a Collection

A collection in MongoDB is the same as a table in SQL databases.

✨ Create Collection

To create a collection in MongoDB, use database object and specify the name of the collection you want to create.

MongoDB will create the collection if it does not exist.

python
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

mycol = mydb["customers"]

⚠️ Important!

In MongoDB, a collection is not created until it gets content!

MongoDB waits until you have inserted a document into the collection.

🔍 Check if Collection Exists

You can check if a collection exist in a database by listing all collections:

python
print(mydb.list_collection_names())

✨ Pro Tip

Or you can check a specific collection by name:

python
collist = mydb.list_collection_names()
if "customers" in collist:
  print("The collection exists.")