How to Drop all the indexes in a Collection using PyMongo?
Last Updated :
10 Jun, 2020
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:
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:
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
try :
client = pymongo.MongoClient()
db = client[ 'GFG' ]
print ( 'connection to the server established' )
except Exception:
print ( 'Failed to Connect to server' )
collection = db.lecture
resp = collection.create_index( "l_id" )
print (resp)
pprint.pprint(collection.index_information())
|
Output:
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
collection.drop_indexes()
pprint.pprint(collection.index_information())
|
Output:
Share your thoughts in the comments
Please Login to comment...