The primary method that allows you to perform aggregation operations using a JavaScript function is mapReduce(). The generic syntax for the collection method is this:
db.<collection>.mapReduce(<map func>,<reduce func>, \
{query:{},out:"<new collection>"})
The first argument is a JavaScript function representing the map phase. In this phase, you define a JavaScript function that calls emit(), which defines the fields included in the operation. The second argument is a JavaScript function that represents the reduce phase. A typical use for this is to produce some sort of accumulation (for example, sum) on the mapped fields.
The third argument is a JSON object with two properties: query and out. query, as you might have guessed, is a filter that limits documents included in the operation. out is the name of a collection into which the results of the operation...