Skip to content

Instantly share code, notes, and snippets.

@jtomaszon
Created November 26, 2025 19:35
Show Gist options
  • Select an option

  • Save jtomaszon/d3a59f04e34fd90f6d39e87aa3931a35 to your computer and use it in GitHub Desktop.

Select an option

Save jtomaszon/d3a59f04e34fd90f6d39e87aa3931a35 to your computer and use it in GitHub Desktop.
redundant-index.js
const coll = db.getCollection("myCollection");
const idxs = coll.getIndexes();
function keyPairs(idx) {
// preserve key order
return Object.keys(idx.key).map(f => [f, idx.key[f]]);
}
function isPrefixIndex(smaller, larger) {
const a = keyPairs(smaller);
const b = keyPairs(larger);
if (a.length >= b.length) return false; // must be strictly shorter to be redundant
for (let i = 0; i < a.length; i++) {
if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) {
return false;
}
}
return true;
}
idxs.forEach(i => {
idxs.forEach(j => {
if (i.name === j.name) return;
// skip “special” indexes where redundancy is tricky
if (i.unique || j.unique || i.sparse || j.sparse ||
i.partialFilterExpression || j.partialFilterExpression) {
return;
}
if (isPrefixIndex(i, j)) {
print(
`Possible redundant index on ${coll.getName()}: ` +
`${i.name} ${tojson(i.key)} is covered by ${j.name} ${tojson(j.key)}`
);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment