const pipeline = [
// Get indexes and the shards that they belong to.
{$indexStats: {}},
// Attach a list of all shards which reported indexes to each document from $indexStats.
{$group: {_id: null, indexDoc: {$push: "$$ROOT"}, allShards: {$addToSet: "$shard"}}},
// Unwind the generated array back into an array of index documents.
{$unwind: "$indexDoc"},
// Group by index name.
{
$group: {
"_id": "$indexDoc.name",
"shards": {$push: "$indexDoc.shard"},
// Convert each index specification into an array of its properties
// that can be compared using set operators.
"specs": {$push: {$objectToArray: {$ifNull: ["$indexDoc.spec", {}]}}},
"allShards": {$first: "$allShards"}
}
},
// Compute which indexes are not present on all targeted shards and
// which index specification properties aren't the same across all shards.
{
$project: {
missingFromShards: {$setDifference: ["$allShards", "$shards"]},
inconsistentProperties: {
$setDifference: [
{$reduce: {
input: "$specs",
initialValue: {$arrayElemAt: ["$specs", 0]},
in: {$setUnion: ["$$value", "$$this"]}}},
{$reduce: {
input: "$specs",
initialValue: {$arrayElemAt: ["$specs", 0]},
in: {$setIntersection: ["$$value", "$$this"]}}}
]
}
}
},
// Only return output that indicates an index was inconsistent, i.e. either a shard was missing
// an index or a property on at least one shard was not the same on all others.
{
$match: {
$expr:
{$or: [
{$gt: [{$size: "$missingFromShards"}, 0]},
{$gt: [{$size: "$inconsistentProperties"}, 0]},
]
}
}
},
// Output relevant fields.
{$project: {_id: 0, indexName: "$$ROOT._id", inconsistentProperties: 1, missingFromShards: 1}}
];