Database Reference
In-Depth Information
$group
The
$group
command does what its name suggests; it groups documents together so you can create an aggregate
of the results. Let's start by creating a simple group command that will list out all the different colors within our
“aggregation” collection. To begin, we create an
_id
document that will list all the elements from our collection that
we want to group. So, we start our pipeline document with the
$group
command and add to it our
_id
document:
{ $group : { _id : "$color" } }
Now you can see we have the
_id
value of
"$color"
. Note that there is a
$
sign in front of the name
color
; this
indicates that the element is a reference from a field in our documents. That gives us our basic document structure, so
let's execute the aggregation:
> db.aggregation.aggregate( { $group : { _id : "$color" } } )
{
"result" : [
{
"_id" : "red"
},
{
"_id" : "maroon"
},
...
{
"_id" : "grey"
},
{
"_id" : "blue"
}
],
"ok" : 1
}
$sum
From the results of the
$group
operator you can see that we have a number of different colors in our result stack. The
result is an array of elements, which contain a number of documents, each with an
_id
value of one of the colors
in the
"color"
field from a document. This doesn't really tell us much, so let's expand what we do with our
$group
command. We can add a count to our group with the
$sum
operator, which can increment a value for each instance of
the value found. To do this, we add an extra value to our
$group
command by providing a name for the new field and
what its value should be. In this case, we want a field called
"count",
as it represents the number of times each color
occurs; its value is to be
{$sum : 1}
, which means that we want to create a sum per document and increase it by 1
each time. This gives us the following document:
{ $group : { _id : "$color", count : { $sum : 1 } }
Let's run our aggregation with this new document:
> db.aggregation.aggregate({ $group : { _id : "$color", count : { $sum : 1 } } }
{
"result" : [