Reputation: 28510
The documentation says that:
When the find() method includes a sort(), the find() method applies the sort() to order the matching documents before it applies the positional $ projection operator.
Arrays can't be sorted, so how would sorting the root documents affect the $
operator?
Can anyone give a practical example?
Upvotes: 0
Views: 252
Reputation: 311895
What this means is that if your query includes a sort on the projected array field, the documents (not the arrays) will be sorted based on the full set of values in the array, not just the projected element.
Sorting documents on array fields works like this (from here):
With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays.
So if you take the example data from the docs you linked to:
{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }
{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] }
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }
A query like the following demonstrates the impact of the rule about projection and sorting:
db.test.find({semester: 1, grades: {$gte: 85}}, {"grades.$": 1})
.sort({grades: -1})
which outputs:
{
"_id" : 3.0,
"grades" : [
85.0
]
}
{
"_id" : 2.0,
"grades" : [
90.0
]
}
{
"_id" : 1.0,
"grades" : [
87.0
]
}
The descending sort on grades
orders the documents based on the largest value of the full array contents, not based on just the projected value.
Upvotes: 4