View Index List
In this final step, you'll learn how to view and manage the list of indexes in your MongoDB database, which is crucial for understanding and optimizing database performance.
Let's continue using our existing database:
use indexlab
To view all indexes in the current database, use the getIndexes()
method:
db.users.getIndexes();
Example output will look like:
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { age: 1 }, name: 'age_1' },
{ v: 2, key: { name: 1, age: 1 }, name: 'name_1_age_1' },
{ v: 2, key: { email: 1 }, name: 'email_1', unique: true },
{ v: 2, key: { email: 1, age: 1 }, name: 'email_1_age_1' }
]
Let's get more detailed information about the indexes:
db.users.getIndexes().forEach(function (index) {
print("Index Name: " + index.name);
print("Index Key: " + JSON.stringify(index.key));
print("Unique: " + (index.unique ? "Yes" : "No"));
print("---");
});
To drop an index, use the dropIndex()
method. Let's remove the index on email:
db.users.dropIndex("email_1");
Verify the index has been removed:
db.users.getIndexes();
You can also drop multiple indexes at once:
// Drop multiple specific indexes
db.users.dropIndexes(["name_1_age_1", "email_1_age_1"]);
To drop all user-created indexes (keeping the default _id index):
db.users.dropIndexes();