Create Collection - PyMongo - Examples


PyMongo - Create a Collection in MongoDB Database

To create a Collection in MongDB Database with Python language using PyMongo,

  1. Create a client to the MongoDB instance.
  2. Provide the name of the database to the client. It returns a reference to the Database.
  3. 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"]

Note: 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)

Output

PyMongo Create Collection in MongoDB Database

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.