Python MongoDB Create Collection
The MongoDB collection is the same as the SQL database table.
Creating a Collection
Use the database object and indicate the name of the collection that you wish to construct to create a MongoDB collection.
If the collection doesn't exist, automatically MongoDB creates the collection.
Example :- Create a collection called "emp" :
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["emp"]
print("Collection created!")
Output :-
Important: A collection is not generated in MongoDB until it gets a document!
MongoDB waits until you insert a document before the collection is truly created.
Check if Collection Exists
You should create a document before you check that a collection exists.
If this is your first time creating a collection then the name of collection will not be displayed until it get atleast a document in it.
The list_collection_names()
method is used to return all available collection names from mongodb, which contains atleast one document.
Example :- Return all collection names from "mydatabase" :
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["emp"]
print(mydb.list_collection_names())
Output :-
Note:- In our case, We have added few documents on it.
Related Links
Delete Collection
By utilising the drop()
method, you can remove a table or collection as it is called in MongoDB.
Example :- Delete the "emp" collection :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
mycol.drop()
print("Collection deleted")
Output :-
If the collection has been dropped successful the drop()
method returns true and false when the collection doesn't exist.
Related Links