-
Type: Task
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: None
-
Labels:None
The Indexing Strategies page (http://docs.mongodb.org/manual/applications/indexes/#use-indexes-to-sort-query-results) has the following statement:
For queries that include a sort that uses a compound index, ensure that all fields before the first sorted field are equality matches.
I verified with Aaron to decode the sentence as such:
For queries that include a sort that uses a compound index, if the sortuses a subset of the index, such as .sort(
{ b: 1 } ), then to ensure
that MongoDB uses the index both to retrieve and sort, the query should use equality conditions for those index fields that precede the
sort index field.
So, for an index of
{ a: 1, b: 1, c:1, d: 1 }- If we have a query with .sort(
{ b: 1 }
), the preceding index field 'a' should be included in the query with an equality condition:
db.collection.find(
{ a: 5 }).sort(
{b:1 })
- If the query condition on the preceding index field is not an equality
condition, MongoDB may sort the documents after it retrieves them
from an index (i.e. the scanAndOrder: true)
db.collection.find( { a: {$gt: 5} } ).sort(
{ b:1 })
As for the query you were specifically wondering about:
db.collection.find(
{ b:5 }).sort(
{ a:1, b:1 })
that query uses a subset in the .sort(); however, the first index field in the sort keys is 'a' and in our index of
{ a: 1, b: 1, c:1, d: 1 }, there is no field
preceding 'a'; so it does not need to be part of the query condition.
- related to
-
DOCS-1521 Sort collections by a sub-element array feature using index gives a correct order
- Closed