Compound indexes should be able to support covered distinct queries, where the distinct key is a non-first element of the index key pattern. Distinct queries are able to use these indexes, but only non-covered plans are generated.
Reproduce with the following:
> var l = db.setLogLevel(5,'query') > db.foo.drop() true > db.foo.ensureIndex({a:1,b:1}) { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.foo.distinct("b",{a:1}) // Should use covered plan on {a:1,b:1}.
From the verbose query log output below, it can be seen that a FETCH <= IXSCAN plan is generated. The FETCH stage here is unnecessary, as the index already contains all information needed in order to generate the set of distinct keys for the requested field.
2015-07-21T13:50:57.081-0400 D QUERY [conn4] Planner: adding solution: FETCH ---fetched = 1 ---sortedByDiskLoc = 0 ---getSort = [{ a: 1 }, { a: 1, b: 1 }, { b: 1 }, ] ---Child: ------IXSCAN ---------keyPattern = { a: 1.0, b: 1.0 } ---------direction = 1 ---------bounds = field #0['a']: [1.0, 1.0], field #1['b']: [MinKey, MaxKey] ---------fetched = 0 ---------sortedByDiskLoc = 0 ---------getSort = [{ a: 1 }, { a: 1, b: 1 }, { b: 1 }, ]
- links to