- Machine Learning
- Machine Learning Tutorial
- Getting Started
- Mean Median Mode
- Standard Deviation
- Percentile
- Data Distribution
- Normal Data Distribution
- Scatter Plot
- Linear Regression
- Polynomial Regression
- Multiple Regression
- Scale
- Train-Test
- Decision Tree
- Confusion Matrix
- Hierarchical Clustering
- Logistic Regression
- Grid Search
- Categorical Data
- K-means
- Bootstrap Aggregation
- Cross Validation
- AUC - ROC Curve
- K-nearest neighbors
- Python MySQL
- Python - MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert
- MySQL Select
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Drop Table
- MySQL Update
- MySQL Limit
- MySQL Join
- Python MongoDB
- Python - MongoDB
- MongoDB Get Started
- MongoDB Create DB
- MongoDB Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Drop Collection
- MongoDB Update
- MongoDB Limit
- Selected Reading
- Q&A
Python MongoDB Create Collection:
Creating a 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.
Example
Create a collection called "customers":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Run example »
Important: In MongoDB, a collection is not created until it gets content!
MongoDB waits until you have inserted a document before it actually creates the collection.
Check if Collection Exists
Remember: In MongoDB, a collection is not created until it gets content, so if this is your first time creating a collection, you should complete the next chapter (create document) before you check if the collection exists!
You can check if a collection exist in a database by listing all collections:
Example
Return a list of all collections in your database:
print(mydb.list_collection_names())
Run example »
Or you can check a specific collection by name:
Example
Check if the "customers" collection exists:
collist = mydb.list_collection_names()
if "customers" in collist:
print("The collection exists.")
Run example »