This rewrite also does not happen when the plan cache is used.
db.c.drop(); assert.commandWorked(db.createCollection("c", {timeseries: {timeField: "t", metaField: "m"}})); assert.commandWorked(db.c.createIndex({"m.b": 1, t: 1})); assert.commandWorked(db.c.createIndex({"m.a": 1, t: 1})); // No bounded sort in this explain jsTestLog(db.c.explain().aggregate([{$sort: {t: 1}}, {$match: {"m.a": 1}}, {$match: {"m.b": 1}}])); // Run it to get it in the plan cache db.c.aggregate([{$sort: {t: 1}}, {$match: {"m.a": 1}}, {$match: {"m.b": 1}}]).toArray(); // Should have one plan cache entry assert.eq(db.system.buckets.c.getPlanCache().list().length, 1); // Plan retrieved from cache, no bounded sort jsTestLog(db.c.explain().aggregate([{$sort: {t: 1}}, {$match: {"m.a": 1}}, {$match: {"m.b": 1}}]));
The issue appears to be here, where we need to handle a multiplan stage and a plan cache stage.
Ideally part of this fix would be to write a test to make sure the rewrite occurs when it comes from the plan cache and from a multiplan stage.