skip to content
Alvin Lucillo

Checking unused indexes

/ 2 min read

In the previous entries, we learned that to reduce the total index storage, we can perform compact or rebuild indexes. Another practical option is to check which indexes are unused. You can do that by running an aggregation stage $indexStats, which returns stats for each index of a collection.

The example below shows that only sha256_1 is used, and it’s only utilized once (see ops: Long("1"))

db.events.aggregate([{ $indexStats: {} }])[
	({
		name: "sha512_1",
		key: { sha512: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("0"), since: ISODate("2026-04-15T12:53:49.835Z") },
		spec: { v: 2, key: { sha512: 1 }, name: "sha512_1" },
	},
	{
		name: "_id_",
		key: { _id: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("0"), since: ISODate("2026-04-15T12:53:49.826Z") },
		spec: { v: 2, key: { _id: 1 }, name: "_id_" },
	},
	{
		name: "sha256_1",
		key: { sha256: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("1"), since: ISODate("2026-04-15T12:53:49.831Z") },
		spec: { v: 2, key: { sha256: 1 }, name: "sha256_1" },
	})
];

accesses.ops is the number of operations that used the index. Notice that when we query by sha256 below, accesses.ops changed from 1 to 2.

db.events.find({ sha256: "2361b047492460e83904e2800dad496211ccf49f233249d493933e1ef118897b" })[
	{
		_id: ObjectId("69df8a5dc4846212f160ff42"),
		tenantID: "tenant-00",
		sha256: "2361b047492460e83904e2800dad496211ccf49f233249d493933e1ef118897b",
		sha512:
			"1391bf993ad2912dcf0ebd3c7f555123c6b3aba9c8a09afbc27fcf86ab4d35eac290a8947e1b63d0f2060aee237270eda19d1881d37bf0536c876178aeea629d",
		status: "open",
		createdAt: ISODate("2026-04-15T12:53:49.835Z"),
		message: "small payload; index growth is driven by sha256 and sha512",
	}
];

db.events.aggregate([{ $indexStats: {} }])[
	({
		name: "sha512_1",
		key: { sha512: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("0"), since: ISODate("2026-04-15T12:53:49.835Z") },
		spec: { v: 2, key: { sha512: 1 }, name: "sha512_1" },
	},
	{
		name: "_id_",
		key: { _id: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("0"), since: ISODate("2026-04-15T12:53:49.826Z") },
		spec: { v: 2, key: { _id: 1 }, name: "_id_" },
	},
	{
		name: "sha256_1",
		key: { sha256: 1 },
		host: "ea3f589b0ffc:27017",
		accesses: { ops: Long("2"), since: ISODate("2026-04-15T12:53:49.831Z") },
		spec: { v: 2, key: { sha256: 1 }, name: "sha256_1" },
	})
];