🍃 MongoDB Tutorial

Manage MongoDB Indexes: getIndexes(), dropIndex() & dropIndexes()

Learn how to list every index on a MongoDB collection with getIndexes(), remove a single index with dropIndex(), and remove several at once with dropIndexes().

Managing MongoDB Indexes

Once you've created a few indexes, you'll need ways to inspect and clean them up.

getIndexes()

Lists every index that currently exists on a collection.

db.student.getIndexes()
// [
//   { v: 2, key: { _id: 1 }, name: '_id_' },
//   { v: 2, key: { roll: 1 }, name: 'roll_1' },
//   { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
//   { v: 2, key: { 'marks.hindi': 1 }, name: 'marks.hindi_1' }
// ]

dropIndex()

Removes a single index by specifying its key pattern.

db.student2.dropIndex({ roll: 1 })
// { nIndexesWas: 2, ok: 1 }

The default _id index can never be dropped:

db.student2.dropIndex({ _id: 1 })
// MongoServerError: cannot drop _id index

dropIndexes()

Removes multiple indexes in a single call — pass the same key pattern(s) used when they were created.

db.student3.dropIndexes({ age: 1, name: 1 })
// { nIndexesWas: 2, ok: 1 }

Common Errors & Troubleshooting

  • dropIndex() failing with "index not found" — the key pattern passed to dropIndex() must match exactly how the index was defined; when unsure, copy the key object straight from getIndexes()'s output instead of retyping it.
  • Dropping an index a production query silently depended on — always run explain() on your important queries first, or check the index name against your application code, before dropping "unused-looking" indexes in production.
  • Trying to drop _id — always fails with cannot drop _id index; this index is permanent by design.

Key Takeaways

  • Always check getIndexes() before dropping anything — it's your source of truth for what exists.
  • dropIndex() removes one index at a time; dropIndexes() removes several.
  • The default _id index is permanent and cannot be dropped by any method.