简体   繁体   中英

mongoDB: does sorting by an inverted non-prefix index subset match the entire index when querying with index prefix?

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}.

https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-non-prefix-subset-of-an-index :

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), eg 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.

The stages are; Index Scan to filter documents and then in-memory sort. So the answer is, it is not leveraging the index for sorting in your scenario.

But if you have an index like:

{a: 1, d: 1, b: 1, c: 1}

Which is Equality, then Sort and then Range. It will leverage the index whichever way your queries are and whichever direction your sort is on d .

Behind the scenes, these are B+ trees!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM