How to create index for MongoDB Collection using Python?

04 Jul, 2022
Prerequisites: MongoDB Python Basics This article focus on the create_index() method of PyMongo library. Indexes makes it efficient to perform query requests as it stores the data in a way that makes it quick & easy to traverse. Let’s begin with the create_index() method:
Importing PyMongo Module: Import the PyMongo module using the command:
Importing PyMongo Module: Import the PyMongo module using the command:
from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).
client = MongoClient(‘localhost’, 27017)
Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.
Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.
mydatabase = client.name_of_the_database
Accessing the Collection: We now select the collection from the database using the following syntax:
Accessing the Collection: We now select the collection from the database using the following syntax:
collection_name = mydatabase.name_of_collection
Creating an index: Now we will create the index using create_index() function. 
Creating an index: Now we will create the index using create_index() function. 
Syntax:
create_index(keys, session=None, **kwargs)

keys: Takes either a single key or a list of (key, direction) pairs.
session (optional): a ClientSession. arguments
**kwargs (optional): any additional index creation option
Example: Sample Database:  
Python3
# Python program to demonstrate# create_index() method  # Importing Libraryfrom pymongo import MongoClient, ASCENDING  # Connecting to MongoDB server# client = MongoClient('host_name', 'port_number')client = MongoClient('localhost', 27017)  # Connecting to the database named# GFGmydatabase = client.GFG  # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student mycollection.create_index('Roll No', unique = True)  # Inserting into Databasemycollection.insert_one({'_id':8 ,                         'name': 'Deepanshu',                         'Roll No': '1008',                         'Branch': 'IT'}) # Inserting with the same Roll no again.# As the Roll no field is the index and# is set to unique it will through the error.mycollection.insert_one({'_id':9 ,                         'name': 'Hitesh',                         'Roll No': '1008',                         'Branch': 'CSE'})
Output:
DuplicateKeyError Traceback (most recent call last) in 36 ‘name’: ‘Hitesh’, 37 ‘Roll No’: ‘1008’, —> 38 ‘Branch’: ‘CSE’}) DuplicateKeyError: E11000 duplicate key error collection: GFG.Student index: Roll No_1 dup key: { : “1008” }
MongoDB Shell:  It raises the DuplicateKeyError as there is already a document that exists with the Roll No 1008 and we are trying to insert another document with the same Roll No. This error occurs because we created an index on the field Roll No and marked it as unique.
khushb99
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python