- Aggregation Operations >
- Map-Reduce >
- Map-Reduce Examples
Map-Reduce Examples¶
On this page
Note
Aggregation Pipeline as Alternative to Map-Reduce
An aggregation pipeline provides better performance and usability than a map-reduce operation.
Map-reduce operations can be rewritten using aggregation
pipeline operators, such as
$group, $merge, and others.
For map-reduce operations that require custom functionality, MongoDB
provides the $accumulator and $function
aggregation operators starting in version 4.4. Use these operators to
define custom aggregation expressions in JavaScript.
In mongosh, the db.collection.mapReduce()
method is a wrapper around the mapReduce command. The
following examples use the db.collection.mapReduce() method.
The examples in this section include aggregation pipeline alternatives without custom aggregation expressions. For alternatives that use custom expressions, see Map-Reduce to Aggregation Pipeline Translation Examples.
Create a sample collection orders with these documents:
Return the Total Price Per Customer¶
Perform the map-reduce operation on the orders collection to group
by the cust_id, and calculate the sum of the price for each
cust_id:
Define the map function to process each input document:
- In the function,
thisrefers to the document that the map-reduce operation is processing. - The function maps the
priceto thecust_idfor each document and emits thecust_idandprice.
- In the function,
Define the corresponding reduce function with two arguments
keyCustIdandvaluesPrices:- The
valuesPricesis an array whose elements are thepricevalues emitted by the map function and grouped bykeyCustId. - The function reduces the
valuesPricearray to the sum of its elements.
- The
Perform map-reduce on all documents in the
orderscollection using themapFunction1map function and thereduceFunction1reduce function:This operation outputs the results to a collection named
map_reduce_example. If themap_reduce_examplecollection already exists, the operation will replace the contents with the results of this map-reduce operation.Query the
map_reduce_examplecollection to verify the results:The operation returns these documents:
Aggregation Alternative¶
Using the available aggregation pipeline operators, you can rewrite the map-reduce operation without defining custom functions:
The
$groupstage groups by thecust_idand calculates thevaluefield (See also$sum). Thevaluefield contains the totalpricefor eachcust_id.The stage output the following documents to the next stage:
Then, the
$outwrites the output to the collectionagg_alternative_1. Alternatively, you could use$mergeinstead of$out.Query the
agg_alternative_1collection to verify the results:The operation returns the following documents:
See also
For an alternative that uses custom aggregation expressions, see Map-Reduce to Aggregation Pipeline Translation Examples.
Calculate Order and Total Quantity with Average Quantity Per Item¶
In the following example, you will see a map-reduce operation on the
orders collection for all documents that have an ord_date value
greater than or equal to 2020-03-01.
The operation in the example:
- Groups by the
item.skufield, and calculates the number of orders and the total quantity ordered for eachsku. - Calculates the average quantity per order for each
skuvalue and merges the results into the output collection.
When merging results, if an existing document has the same key as the new result, the operation overwrites the existing document. If there is no existing document with the same key, the operation inserts the document.
Example steps:
Define the map function to process each input document:
- In the function,
thisrefers to the document that the map-reduce operation is processing. - For each item, the function associates the
skuwith a new objectvaluethat contains thecountof1and the itemqtyfor the order and emits thesku(stored in thekey) and thevalue.
- In the function,
Define the corresponding reduce function with two arguments
keySKUandcountObjVals:countObjValsis an array whose elements are the objects mapped to the groupedkeySKUvalues passed by map function to the reducer function.- The function reduces the
countObjValsarray to a single objectreducedValuethat contains thecountand theqtyfields. - In
reducedVal, thecountfield contains the sum of thecountfields from the individual array elements, and theqtyfield contains the sum of theqtyfields from the individual array elements.
Define a finalize function with two arguments
keyandreducedVal. The function modifies thereducedValobject to add a computed field namedavgand returns the modified object:Perform the map-reduce operation on the
orderscollection using themapFunction2,reduceFunction2, andfinalizeFunction2functions:This operation uses the
queryfield to select only those documents withord_dategreater than or equal tonew Date("2020-03-01"). Then it outputs the results to a collectionmap_reduce_example2.If the
map_reduce_example2collection already exists, the operation will merge the existing contents with the results of this map-reduce operation. That is, if an existing document has the same key as the new result, the operation overwrites the existing document. If there is no existing document with the same key, the operation inserts the document.Query the
map_reduce_example2collection to verify the results:The operation returns these documents:
Aggregation Alternative¶
Using the available aggregation pipeline operators, you can rewrite the map-reduce operation without defining custom functions:
The
$matchstage selects only those documents withord_dategreater than or equal tonew Date("2020-03-01").The
$unwindstage breaks down the document by theitemsarray field to output a document for each array element. For example:The
$groupstage groups by theitems.sku, calculating for each sku:The
$projectstage reshapes the output document to mirror the map-reduce’s output to have two fields_idandvalue. The$projectsets:The
$unwindstage breaks down the document by theitemsarray field to output a document for each array element. For example:The
$groupstage groups by theitems.sku, calculating for each sku:The
$projectstage reshapes the output document to mirror the map-reduce’s output to have two fields_idandvalue. The$projectsets:Finally, the
$mergewrites the output to the collectionagg_alternative_3. If an existing document has the same key_idas the new result, the operation overwrites the existing document. If there is no existing document with the same key, the operation inserts the document.Query the
agg_alternative_3collection to verify the results:The operation returns the following documents:
See also
For an alternative that uses custom aggregation expressions, see Map-Reduce to Aggregation Pipeline Translation Examples.