Open In App

How to create index for MongoDB Collection using Python?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Importing PyMongo Module: Import the PyMongo module using the command:
from pymongo import MongoClient
  1. If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
  2. 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)
  1. 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
  1. Accessing the Collection: We now select the collection from the database using the following syntax:
collection_name = mydatabase.name_of_collection
  1. 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: python-mongodb-insert-one-21 

Python3




# Python program to demonstrate
# create_index() method
 
 
# Importing Library
from pymongo import MongoClient, ASCENDING
 
 
# Connecting to MongoDB server
# client = MongoClient('host_name', 'port_number')
client = MongoClient('localhost', 27017)
 
 
# Connecting to the database named
# GFG
mydatabase = client.GFG
 
 
# Accessing the collection named
# gfg_collection
mycollection = mydatabase.Student
 
mycollection.create_index('Roll No', unique = True)
 
 
# Inserting into Database
mycollection.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:

python-mongodb-index

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.



Last Updated : 04 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads