MongoDB documentation
https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-on-multiple-fields:
For a query to use a compound index for a sort, the specified sort direction for all keys in the cursor.sort() document must match the index key pattern or match the inverse of the index key pattern. For example, an index key pattern { a: 1, b: -1 } can support a sort on { a: 1, b: -1 } and { a: -1, b: 1 } but not on { a: -1, b: -1 } or {a: 1, b: 1}.
An index can support sort operations on a non-prefix subset of the index key pattern. To do so, the query must include equality conditions on all the prefix keys that precede the sort keys.
Question
OK, so given an index {a: 1, b: 1, c: 1, d: 1}
, the first quote says I can do sorts {a: 1, b: 1, c: 1, d: 1}
and its inverse {a: -1, b: -1, c: -1, d: -1}
. Awesome. And the second quote says I can use the index for querying with index prefixes and sorting by an index "suffix" (if I can coin that term), e.g. db.Foo.find({a: 52, b: {$lt: 5}, c: {$gte: 12}}).sort({d: 1})
. Also awesome.
My question then is, will db.Foo.find({a: 52, b: {$lt: 5}, c: {$gte: 12}}).sort({d: -1})
(note the descending sort on d
) match the index {a: 1, b: 1, c: 1, d: 1}
? Will it invert the index behind the scenes and use {a: -1, b: -1, c: -1, d: -1}
? Near as I can tell, mongo's documentation doesn't cover this case.