How to Show Indexes in MongoDB: Syntax and Examples
To show indexes in MongoDB, use the
db.collection.getIndexes() method which returns all indexes on the specified collection. Alternatively, you can use db.collection.getIndexKeys() to see just the index keys.Syntax
The main command to list indexes on a collection is db.collection.getIndexes(). Replace collection with your collection name. This returns an array of index documents with details.
Another command is db.collection.getIndexKeys(), which returns only the index key patterns.
mongodb
db.collection.getIndexes() db.collection.getIndexKeys()
Example
This example shows how to create a collection, add an index, and then list all indexes on it.
mongodb
use testdb // Create collection and insert a document db.users.insertOne({name: "Alice", age: 30}) // Create an index on the 'age' field db.users.createIndex({age: 1}) // Show all indexes on 'users' collection const indexes = db.users.getIndexes() printjson(indexes)
Output
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testdb.users"
},
{
"v" : 2,
"key" : {
"age" : 1
},
"name" : "age_1",
"ns" : "testdb.users"
}
]
Common Pitfalls
One common mistake is trying to use show indexes as a shell command, which is not valid in MongoDB shell. Always use db.collection.getIndexes().
Another pitfall is forgetting to specify the correct collection name, which will cause errors or empty results.
mongodb
/* Wrong way - invalid shell command */ show indexes /* Right way */ db.users.getIndexes()
Quick Reference
| Command | Description |
|---|---|
| db.collection.getIndexes() | Lists all indexes on the collection with details |
| db.collection.getIndexKeys() | Lists only the index key patterns |
| db.collection.createIndex({field: 1}) | Creates an ascending index on a field |
| db.collection.dropIndex('indexName') | Removes an index by name |
Key Takeaways
Use db.collection.getIndexes() to list all indexes on a MongoDB collection.
Always specify the correct collection name before calling index commands.
Avoid using shell commands like 'show indexes' which are invalid in MongoDB shell.
Use getIndexKeys() if you only need the index key patterns without full details.
Creating indexes before querying can improve performance but always check existing indexes first.