Contents
PyMongo – Create a Collection in MongoDB Database
To create a Collection in MongDB Database with Python language using PyMongo,
- Create a client to the MongoDB instance.
- Provide the name of the database to the client. It returns a reference to the Database.
- Provide your new collection name as index to the database reference.
It returns a reference to the Collection. When you insert a document for the first time to the collection, the new collection is implicitly created.
Examples
1. Create a MongoDB collection named “testers”
In the following program, we created a collection named testers.
Python Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# Use database named "organisation"
mydb = myclient["organisation"]
# New collection named "testers"
mycol = mydb["testers"]
CopyNote: Collection is actually created when there is content in the collection. So, only when there is atleast one document inside the collection, you could see that the collection is created when you run list_collection_names() function.
In the following example, we have created the collection, inserted a document and then listed the collections.
Python Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# Use database named "organisation"
mydb = myclient["organisation"]
# Use collection named "testers"
mycol = mydb["testers"]
# A document
tester = { "name": "Ram", "address": "India" }
# Insert a document to the collection
x = mycol.insert_one(tester)
print("List of Collections\n--------------------")
# List the collections
for coll in mydb.list_collection_names():
print(coll)
CopyOutput
In the above screenshot, we have run a python program to list the collections present in MongoDB instance. Then we ran the above python program, where we created a mongodb collection and inserted a document in it.
Summary
In this PyMongo Tutorial, we learned how to create a collection in a MongoDB database, with examples.