How to create index for MongoDB Collection using Python?
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:
from pymongo import MongoClient
- 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.
mydatabase = client.name_of_the_database
- 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.
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
from pymongo import MongoClient, ASCENDING
client = MongoClient( 'localhost' , 27017 )
mydatabase = client.GFG
mycollection = mydatabase.Student
mycollection.create_index( 'Roll No' , unique = True )
mycollection.insert_one({ '_id' : 8 ,
'name' : 'Deepanshu' ,
'Roll No' : '1008' ,
'Branch' : 'IT' })
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.
Last Updated :
04 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...