Each time we make changes to a collection, any indexes associated with that collection must also be updated. In this way, unnecessary indexes can slow down the performance of certain CRUD operations. This is why it is important to review our indexes and remove any that are redundant or not being used.
Suppose, after some reflection, we discovered that a compound index can handle all the queries we need to make, instead of the single field indexes we originally were relying on. Once we’ve created the compound index, it would be a good idea to identify and remove any unnecessary indexes.
First, we can use the .getIndexes()
method to see all of the indexes that exist for a particular collection.
Consider a collection called students
that has multiple indexes:
db.students.getIndexes();
Might output:
[ { v : 1, key : { _id : 1 }, name : '_id_' }, { v : 1, key : { sports : -1 }, name : 'sports_-1' }, { v : 1, key : { sports : -1, graduation year : -1 }, name : 'sports_-1_graduation_year_-1' } ]
Now that we have a list of our indexes for the students
collection, we can see that both the second and third indexes index the sports
key in descending order. Since compound indexes can support queries on any of the prefixed fields, our third index, named 'sports_-1_graduation_year_-1'
, can support queries on both sports
and graduation_year
.
This means that our second index, 'sports_-1'
, is redundant. MongoDB gives us another method, .dropIndex()
, that allows us to remove an index, without modifying the original collection. We can use it to delete the 'sports_-1'
index:
db.students.dropIndex('sports_-1');
The above command would delete the index, and then we can confirm by running db.students.getIndexes();
again:
[ { v : 1, key : { _id : 1 }, name : '_id_' }, { v : 1, key : { sports : -1, graduation year : -1 }, name : 'sports_-1_graduation_year_-1' } ]
Getting rid of unnecessary indexes can free up disk space and speed up the performance of write operations, so as you start to use indexes more, it is worth regularly scrutinizing them to see which, if any, you can remove.
Let’s practice removing an index from our restaurants
collection!
Instructions
We’ve created several indexes throughout this lesson. Run the .getIndexes()
method to take inventory of all the indexes we have so far.
Since we have one compound index that references both borough
and cuisine
, the indexes named borough_1
and cuisine_-1
are now redundant. Use the .dropIndex()
method to delete the borough_1
index from the listingsAndReviews
collection.