Indexing in MongoDB using Python

By creating indexes in a MongoDB collection, query performance is enhanced because they store the information in such a manner that traversing it becomes easier and efficient. There is no need for a full scan as MongoDB can search the query through indexes. Thus it restricts the number of documents that need to be checked for query criteria. 
 

Syntax– create_index([str1, direction], [str1, direction]……., optional)  

Parameters are: 
 

  • str : string used for naming index, it can be one or more than one
  • direction : can be one or many directions, it has to be one of these directions- descending, ascending, hashed, geosphere, geohaystack, geo2d or text

Example 1:



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from pymongo import MongoClient
# Create a pymongo client 
client = MongoClient('localhost', 27017
    
# database instance 
db = client['GFG'
    
# collection instance 
doc = db['Student'
  
# Creating a single field index
res = doc.create_index("index_created")
print(res)

chevron_right


Output: 
 

index_created_1

Example 2:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from pymongo import MongoClient
# Create a pymongo client 
client = MongoClient('localhost', 27017
    
# database instance 
db = client['GFG'
    
# collection instance 
doc = db['Student'
  
# Creating a single field index in descending order
res = doc.create_index([ ("index_descending", -1) ])
print(res)

chevron_right


Output:

index_descending_-1

Example 3:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from pymongo import MongoClient,, ASCENDING, DESCENDING 
# Create a pymongo client 
client = MongoClient('localhost', 27017
    
# database instance 
db = client['GFG'
    
# collection instance 
doc = db['Student'
  
# Creating a compund field index in descending order
res = doc.create_index(
[
("ascending_index", 1),
("second_descnding_indexed", DESCENDING)
]
)
print(res)

chevron_right


Output:

ascending_index_1
second_descnding_indexed_DESCENDING

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.