Last Updated : 15 Jul, 2025
In PyMongo, the drop_indexes() method is used to remove all non-default indexes from a collection. It helps developers clean up or reset indexing strategies, especially during optimization or testing. The method retains the default _id index, which cannot be dropped.
Syntaxcollection.drop_indexes()
Sample database used: Viewing Existing IndexesNote: drop_indexes() method does not take any parameters, it simply removes all indexes on the collection.
By default, every MongoDB collection has an index on the _id field to uniquely identify each document. Even if you delete all other indexes, the _id index will still remain and cannot be removed.
To list all current indexes on a collection, run:
Where,
This code creates an index on the l_id field. It then prints the auto-generated name of the new index and displays all indexes present in the collection using index_information().
Python
import pprint
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client['GFG']
print("Connection to the server established.")
collection = db['lecture']
# Create an index on the 'l_id' field
index_name = collection.create_index("l_id")
# Print the auto-generated index name
print("Created Index Name:", index_name)
# Display all indexes on the collection
print("\nCurrent Indexes:")
pprint.pprint(collection.index_information())
Output
Snapshot of Terminal showing Output of Adding Index to a Collection Example 2:In this Example all indexes are removed except default _id index using the drop_indexes() method, then prints the remaining indexes using index_information().
Python
import pprint
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client['GFG']
collection = db['lecture']
# Drop all indexes except the default _id index
collection.drop_indexes()
# Display current indexes on the collection
print("\nRemaining Indexes after drop_indexes():")
pprint.pprint(collection.index_information())
Output
Snapshot of Terminal showing Output of Deleting Index of a CollectionRelated Articles:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4