Besides MapReduce, aggregation in MongoDB can also be performed using the group()
method on a collection. group()
can be viewed as a short-circuit approach for doing MapReduce. It is easier to learn and use (easier because it is a lot similar to using GROUP BY
in SQL). The group()
method takes the following parameters:
key:
Specifies the key or set of keys by which the documents will be grouped.initial:
The base aggregator counter, specifies initial values before aggregation.reduce:
A reduce that aggregates the documents. It takes two arguments, the current document being iterated over, and the aggregation counter.
In addition to these, group()
can also receive the following optional arguments:
cond:
A query object. Only the documents matching this query will be used in grouping.finalize:
A function that runs on each item in the result set (before returning the item). It can either modify or replace the returning item.
In the next section, we...