How to Drop Index in MongoDB: Syntax and Examples
To drop an index in MongoDB, use the
db.collection.dropIndex() method with the index name or key specification. This removes the specified index from the collection without affecting the data.Syntax
The dropIndex() method removes a specific index from a MongoDB collection.
db.collection.dropIndex(index): Drops the index specified byindex.indexcan be the index name as a string or the index key pattern as an object.
javascript
db.collection.dropIndex(index)
Example
This example shows how to drop an index named username_1 from the users collection.
javascript
use mydatabase // Create an index on the username field db.users.createIndex({ username: 1 }) // Drop the index by name const result = db.users.dropIndex('username_1') printjson(result)
Output
{ "nIndexesWas": 2, "ok": 1 }
Common Pitfalls
Common mistakes when dropping indexes include:
- Using the wrong index name or key pattern, which causes an error.
- Trying to drop the default _id index, which is not allowed.
- Not checking if the index exists before dropping it.
Always verify the index name with db.collection.getIndexes() before dropping.
javascript
/* Wrong index name - causes error */ db.users.dropIndex('wrong_index_name') /* Correct way: check indexes first */ const indexes = db.users.getIndexes() printjson(indexes) // Then drop the correct index // db.users.dropIndex('username_1')
Quick Reference
| Command | Description |
|---|---|
| db.collection.dropIndex(indexName) | Drops the index by its name |
| db.collection.dropIndex({ field: 1 }) | Drops the index by key pattern |
| db.collection.getIndexes() | Lists all indexes on the collection |
| Cannot drop _id index | The default _id index cannot be removed |
Key Takeaways
Use db.collection.dropIndex() with the correct index name or key to remove an index.
Check existing indexes with db.collection.getIndexes() before dropping.
You cannot drop the default _id index on a collection.
Dropping an index does not affect the data in the collection.
Provide the exact index name or key pattern to avoid errors.