- Aggregation >
- Map-Reduce >
- Map-Reduce Examples
Map-Reduce Examples¶
On this page
In the mongo shell, the db.collection.mapReduce()
method is a wrapper around the mapReduce command. The
following examples use the db.collection.mapReduce() method:
Aggregation Pipeline as Alternative
Aggregation pipeline provides better performance and a more coherent interface than map-reduce.
Various map-reduce expressions can be
rewritten using aggregation pipeline operators, such as $group,
$merge, etc.
The example below includes aggregation pipeline alternatives.
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 using$sum. Thevaluefield contains the totalpricefor eachcust_id.This stage outputs these 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 these documents:
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
$unwindsstage 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
qtyfield. Theqtyfield contains the totalqtyordered per eachitems.skuusing$sum. - The
orders_idsarray. Theorders_idsfield contains an array of distinct order_id’s for theitems.skuusing$addToSet.
- The
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 these documents: