Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 10 Jun, 2020
Geek Week

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




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()) 

Output:

python-mongodb-drop-all-indexes-2

Example 2: Deleting the Index from the Collection




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()) 

Output:

python-mongodb-drop-all-indexes-3

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :