Quick revision
The short answer
I would clean up in evidence-based steps: collect $indexStats from every member over a long enough period to find indexes with no or very few accesses, find indexes that are redundant because they are a prefix of another index, hide each candidate with hideIndex so the optimizer ignores it while it is still maintained, and drop it only after a quiet period with no regressions. To stop the problem returning, every index gets an owner and a reason and is created through migration code, never by hand, and we track index size and working set against RAM, because indexes that do not fit in memory slow every operation.
What to remember
In this answer, we saw that every index adds work to every write and competes for cache memory, which explains climbing write latency and memory use. We found unused indexes with $indexStats collected from all members over a full business cycle, found redundant prefix indexes while respecting unique, TTL and partial options, and removed candidates safely by hiding them first and dropping only after a quiet period. To keep it clean, indexes became owned code in migrations, and we watch index size and working set against RAM.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would clean up in evidence-based steps: collect $indexStats from every member over a long enough period to find indexes with no or very few accesses, find indexes that are redundant because they are a prefix of another index, hide each candidate with hideIndex so the optimizer ignores it while it is still maintained, and drop it only after a quiet period with no regressions. To stop the problem returning, every index gets an owner and a reason and is created through migration code, never by hand, and we track index size and working set against RAM, because indexes that do not fit in memory slow every operation.
Background to this question
Index sprawl is a slow disease. Each index was added for a good reason by someone who needed a query to be fast, and nobody ever removes one, because removing an index is scary and adding one feels free. But every index is updated on every insert and on every update that touches its fields, and every index competes for the same memory. With 40 to 60 indexes per collection, a single insert may update 50 B-trees. A senior engineer is asked this because the cleanup is risky if done carelessly and pointless if it is not followed by governance. In this answer, we will recap why indexes cost writes and memory, then find unused and redundant indexes, remove them safely with hidden indexes, and put ownership and monitoring in place.
1A Quick Recap: What Each Index Costs
An index speeds up reads that match it and slows down every write. Inserting a document means inserting one entry into every index on the collection, or many entries for a multikey index on an array. Updating a field means updating every index that includes that field. Deleting a document removes its entries everywhere. So write latency grows roughly with the number of indexes the write must touch.
Memory is the second cost. WiredTiger, MongoDB's storage engine, keeps frequently used index and data pages in its cache. The set of pages the workload touches regularly is called the working set. When the indexes alone are bigger than the cache, normal operations start reading index pages from disk, and every query and write slows down, not just the ones that use the bloated indexes.
2Finding Unused Indexes With $indexStats
MongoDB counts how often each index is used. The $indexStats aggregation stage returns, per index, the number of operations that used it and the time counting started.
There are two catches. The counters reset when a node restarts and are per node, so we must collect them from every member, including secondaries that serve reads such as reporting, and combine them. And the period must be long enough to include rare but important jobs: a month-end report or a yearly audit that runs once may be the only user of an index. So we gather stats over at least one full business cycle, often 30 to 90 days, and store snapshots so restarts do not erase history.
3Finding Redundant Prefix Indexes
An index can serve any query on a prefix of its key. So if {customerId: 1, status: 1} exists, a separate {customerId: 1} is usually redundant: every query that uses the single-field index can use the compound one. These duplicates are common when different teams add indexes without seeing the full list.
Notice the exceptions before calling something redundant. A prefix index with different options is not a duplicate: a unique index enforces a rule, a TTL index deletes data, a partial index or one with a collation behaves differently. And a smaller index can still be faster for some queries because it is more compact, which is why we confirm with the usage stats rather than drop by rule alone.
4Removing Safely: Hide, Watch, Then Drop
Dropping an index is instant, but rebuilding a 2 GB index on a busy collection takes a long time and a lot of resources, so a mistaken drop can cause hours of degraded service. Since MongoDB 4.4 we can hide an index instead. A hidden index is still maintained on every write, but the query planner ignores it, so we can see the effect of removing it with a one-command rollback.
- Collect $indexStats from all members30 to 90 days, snapshots kept
- Unused or a redundant prefix?check options: unique, TTL, partialYesMark as candidateNoKeep it
- Tell the owning team, then hideIndexplanner ignores it, writes still maintain it
- Any regression in the slow log?YesunhideIndex and record why it is neededNodropIndex after the quiet period
4 steps in order. Play them, or step through them one at a time.
The process for each candidate is: announce it to the owning teams, hide it, watch slow queries and latency across a full cycle, and then drop. We work in small batches, a few indexes per collection at a time, so if a regression appears we know which index caused it. Notice that hiding does not yet reduce write cost, because the hidden index is still maintained; the gain arrives at the drop.
5Ownership: Indexes as Code
Cleaning up once is not enough. The reason we have 60 indexes is that anyone could create one by hand in production and nobody recorded why. So I would make every index part of the application's migration code, reviewed like any schema change, with a comment naming the query it serves and the owning team. With Spring Data MongoDB, automatic index creation from annotations is off by default since version 3.0, and that is the right default for production; migrations, with a tool such as Mongock or a startup step that calls createIndex explicitly, make indexes visible in version control.
Then we compare the migration-defined list with the live indexes regularly, and any index that exists only in production is flagged. New index requests go through a short review that asks which query needs it, whether an existing index can be extended instead, and what the write cost will be.
6Watching Index Size Against Memory
Finally, we monitor the number that matters most: total index size and working set versus the WiredTiger cache. We track totalIndexSize per collection, cache usage, and the rate of pages read into the cache from disk. If index size grows toward the cache size, we act before latency does, by removing indexes, using partial indexes so only relevant documents are indexed, or adding memory.
In the example above, 96 GB of indexes on a 64 GB cache is the real reason every operation is slow. If the cleanup removes 25 indexes and 40 GB, the hot indexes fit in memory again, and both write latency and read latency improve, which is the result we report to the teams to keep their support for the governance that follows.
7Follow-up questions
Is it safe to rely on $indexStats alone?
No. It shows usage since the last restart on one node. We combine it with stats from all members, a long observation window, knowledge of rare jobs, and the hide-before-drop step, which is the real safety net.
Can hiding an index affect writes?
Hiding does not change writes at all; a hidden index is still updated. That is why unhiding is instant. It also means a hidden unique index still enforces uniqueness, so hiding is not a way to test removing a constraint.
What about the _id index?
It cannot be dropped or hidden. It is required on every collection, so it is never a candidate.
8Conclusion
In this answer, we saw that every index adds work to every write and competes for cache memory, which explains climbing write latency and memory use. We found unused indexes with $indexStats collected from all members over a full business cycle, found redundant prefix indexes while respecting unique, TTL and partial options, and removed candidates safely by hiding them first and dropping only after a quiet period. To keep it clean, indexes became owned code in migrations, and we watch index size and working set against RAM.
Open with
First I would explain why it matters: every index is updated on every write that touches it, so sixty indexes means sixty B-trees per insert, and they all compete for the WiredTiger cache.
Then, if they want more
If total index size is bigger than the cache, every operation slows down. Then I would find candidates with evidence. I run $indexStats on every member, including secondaries that serve reads, and keep snapshots over thirty to ninety days, because counters reset on restart and some indexes only serve a month-end job.
Indexes with zero or very few accesses are candidates. I also look for redundant prefixes, like customerId alone when customerId plus status exists, but I keep any that are unique, TTL, partial or use a collation. For removal I use hideIndex, available since 4.4: the planner ignores the index but it is still maintained, so unhide is an instant rollback.
We hide a few at a time, tell the owning teams, watch the slow query log for a few weeks, then drop.
To stop it recurring, every index lives in migration code with an owner and the query it serves, nobody creates indexes by hand, and we monitor index size and working set against RAM so we act before latency does.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- MongoDB manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your MongoDB clusters have 40 to 60 indexes per collection, many created by different...": https://scrivio-interview-library.netlify.app/databases/mongodb/3f5db53bd5/