Database Reference
In-Depth Information
$sort
As you've just seen, the $limit command can change which documents are returned in the result because it reflects
the order in which the documents were originally output from the execution of the aggregation. This can be fixed with
the advent of the $sort command. We simply need to apply a sort on a particular field before providing the limit in
order to return the same set of limited results. The $sort syntax is the same as it is for a normal query; you specify
documents that you wish to sort by, positive for ascending and negative for descending. To show how this works, let's
run our query with and without the match and a limit of 1. You will see that with the $sort prior to the $limit we can
return documents in the same order.
This gives us the first query of
[
{ $group : { _id : { color: "$color", transport: "$transport"} , count : { $sum : 1 } } },
{ $sort : { _id :1 } },
{ $limit : 5 }
]
The result of this query is:
{
"result" : [
{
"_id" : {
"color" : "black",
"transport" : "autombile"
},
"count" : 18
}
],
"ok" : 1
}
The second query looks like this:
[
{ $match : { num : { $gt : 500 } } },
{ $group : { _id : { color: "$color", transport: "$transport"} , count : { $sum : 1 } } },
{ $sort : { _id :1 } },
{ $limit : 1 }
]
The result of this query is
{
"result" : [
{
"_id" : {
"color" : "black",
"transport" : "autombile"
},
"count" : 9
}
 
Search WWH ::




Custom Search