Database Reference
In-Depth Information
{
"_id" : "red",
"count" : 90
},
{
"_id" : "maroon",
"count" : 91
},
...
{
"_id" : "grey",
"count" : 91
},
{
"_id" : "blue",
"count" : 91
}
],
"ok" : 1
}
Now you can see how often each color occurs. We can further expand what we are grouping by adding extra
elements to the _id document. Let's say we want to find groups of "color" and "transport" . To do that, we can
change _id to be a document that contains a subdocument of items as follows:
{ $group : { _id : { color: "$color", transport: "$transport"} , count : { $sum : 1 } } }
If we run this we get a result that is about 50 elements long, far too long to display here. There is a solution to this,
and that's the $limit operator.
$limit
The $limit operator is the next pipeline operator we will work with. As its name implies, $limit is used to limit the
number of results returned. In our case we want to make the results of our existing pipeline more manageable, so let's
add a limit of 5 to the results. To add this limit, we need to turn our one document into an array of pipeline documents.
[
{ $group : { _id : { color: "$color", transport: "$transport"} , count : { $sum : 1 } } },
{ $limit : 5 }
]
This will give us the following results:
> db.aggregation.aggregate( [ { $group : { _id : { color: "$color", transport: "$transport"} , count
: { $sum : 1 } } }, { $limit : 5 } ] )
{
"result" : [
{
"_id" : {
"color" : "maroon",
"transport" : "motorbike"
 
Search WWH ::




Custom Search