How to Drop all the indexes in a Collection using PyMongo?

Prerequisites: MongoDB and Python

With the help of drop_indexes() method we can drop all the indexes in a Collection. No parameter is passed in the method. Only default index _id can not be deleted. All the Non _id indexes will be the drop by this method. It means we can only drop the index which we have created.

Syntax:

db.collection_name.drop_indexes()

Sample database used:

python-mongodb-sample-database5



By default, each collection has the _id index. All collections compulsorily have at least one index. If all indexes are removed, then a new index will be automatically generated. We can see the indexes present by running the following command:

python-mongodb-drop-all-indexes-1

Now, we can run the following code to add a new Index called newIndex to the collection, given that the mongo server is running:

Example 1: Adding an Index to the Collection

filter_none

edit
close

play_arrow

link
brightness_4
code

import pprint 
import pymongo 
    
# connection 
try
    client = pymongo.MongoClient() 
    db = client['GFG'
    print('connection to the server established'
        
except Exception: 
    print('Failed to Connect to server'
  
collection = db.lecture 
  
# creating an index 
resp = collection.create_index("l_id"
    
# printing the auto generated name  
# returned by MongoDB 
print(resp) 
    
# index_information() is analogous  
# to getIndexes 
pprint.pprint(collection.index_information()) 

chevron_right


Output:

python-mongodb-drop-all-indexes-2

Example 2: Deleting the Index from the Collection

filter_none

edit
close

play_arrow

link
brightness_4
code

import pprint 
import pymongo 
  
    
try
    client = pymongo.MongoClient() 
    db = client['GFG'
    print('connection to the server established'
  
except Exception: 
    print('Failed to Connect to server'
  
collection = db.lecture 
    
# dropping the index using autogenerated 
# name from MongoDB 
collection.drop_indexes() 
    
# printing the indexes present on the collection 
pprint.pprint(collection.index_information()) 

chevron_right


Output:

python-mongodb-drop-all-indexes-3




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.