dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/mongodb/#83
Script #83
mongodb
Performanceread-onlyMin Version: 3.2

Find Unused Indexes in MongoDB ($indexStats)

Lists never-used indexes per collection. Offers cleanup candidates to cut write cost and memory use.

#indexStats#unused-index#cleanup
mongodb · javascript
const out = [];
db.getCollectionInfos({ type: "collection" }).forEach(c => {
  db.getCollection(c.name).aggregate([{ $indexStats: {} }]).forEach(i => {
    if (i.name !== "_id_" && i.accesses.ops === 0) {
      out.push({ collection: c.name, index: i.name, key: JSON.stringify(i.key), since: i.accesses.since });
    }
  });
});
console.table(out);
Operational Notes & Remediation Guidance

Indexes with low or zero access counts consume memory in WiredTiger cache and slow down write operations.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 3.2).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.