MongoDB’s aggregation framework is extremely powerful in that it allows you to pipe the results of one aggregation operator into another multiple times. This data set shows an example:
{o_id:"A", value:50, type:"X"}
{o_id:"A", value:75, type:"X"}
{o_id:"B", value:80, type:"X"}
{o_id:"C", value:45, type:"Y"}
The following aggregation operator set would pipeline the results of the $match
into the $group
operator and then return the grouped set in the results
parameter of the callback function. Notice that when referencing the values of fields in documents, the fieldname is prefixed by a dollar sign—for example, $o_id
and $value
. This syntax tells the aggregate framework to treat it as a field value instead of a string.
aggregate([{$match:{type:"X"}},
{$group:{set_id:"$o_id", total: {$sum: "$value"}}},
function(err, results){});
After the $match
operator completes, these documents are applied to $group
:
{o_id:"A", value:50, type:"X"}
{o_id:"A", value:75, type:"X"}
{o_id:"B", value:80, type:"X"}
Then after the $group
operator is applied, a new array of objects is sent to the callback function with set_id
and total
fields, as shown below:
{set_id:"A", total:"125"}
{set_id:"B", total:"80"}
Table 15.3 lists the aggregation commands you can include in the operators
parameter to the aggregate()
method.