dropIndex() - delete the specified index
Safely deletes the specified index of the collection.
Overview
The dropIndex() method is used to delete the specified index of the collection. Support security check and prohibit deletion of _id index.
Usage Scenario:
- Delete indexes that are no longer used
- Optimize index structure
- Cleanup before index rebuild
- Test and development environment cleanup
Syntax
Parameters
indexName (required)
The name of the index to delete.
Type: String
Example:
"email_1"- single field index"email_unique"- Index of custom name"user_status_idx"- compound index
Restrictions:
- ❌ Cannot delete
_id_index (MongoDB enforced restriction) - ❌ cannot be an empty string
Return value
Type: Promise<Object>
Format:
Code Example
Example 1: Delete a single index
Example 2: Delete after checking
Example 3: Error handling
Example 4: Batch deletion process
Example 5: Safe delete mode
Error handling
1. Index does not exist
Error code: MONGODB_ERROR
Message: "Index does not exist: {indexName}"
Solution:
2. Disable deletion of _id index
Error code: INVALID_ARGUMENT
Message: "Deletion of _id index is not allowed"
Reason: MongoDB enforces that each collection must have an _id index
Solution:
3. Insufficient permissions
Error code: MongoDB error Message: "not authorized"
Solution: Make sure the database user has dropIndex permissions
Security Advice
1. Backup before deletion
2. Precautions for production environment
3. Rollback plan
Related methods
dropIndexes()- delete all indexescreateIndex()- Create indexlistIndexes()- list all indexes- Complete Guide to Index Management - Comprehensive Documentation on Index Management
dropIndexes() - drop all indexes
Delete all indexes of the collection (except the _id index).
Syntax (dropIndexes() - drop all indexes)
Parameters (dropIndexes() - drop all indexes)
No parameters.
Return value (dropIndexes() - delete all indexes)
Type: Promise<Object>
Format:
Code example (dropIndexes() - drop all indexes)
Example 1: Delete all indexes
Example 2: Rebuild all indexes
Example 3: Processing when the collection does not exist
Security advice (dropIndexes() - drop all indexes)
IMPORTANT WARNING:
- ⚠️ This operation will delete all custom indexes
- ⚠️ May seriously affect query performance
- ⚠️ Use with caution in production environment
Recommended Practice: