Case study II of MongoDB mapReduce
Example 2. Find the total number of orders corresponding to an item in an order and the average sales quantity of each order for this item
1. Take a look at the order table first. The data structure of orders is as follows.
There are six such data items. As follows, only the field items is listed.
2. The map function is given below.
Var mapFunction2 = function () {for (var idx = 0; idx < this.items.length; idx++) {var key = this.items [IDX] .sku; var value = {count: 1this.items [IDX] .qty}; emit (key, value);}}
3. Write reduce function
Var reduceFunction2 = function (keySKU, countObjVals) {reducedVal = {count: 0, qty: 0}; for (var idx = 0; idx < countObjVals.length; idx++) {reducedVal.count + = countObjVals [IDX] .count; reducedVal.qty + = countObjVals [IDX] .qty;} return reducedVal;}
4. Write finalize function
Var finalizeFunction2 = function (key, reducedVal) {reducedVal.avg = reducedVal.qty/reducedVal.count;return reducedVal;}
5. Execute the mapReduce function
6. View the results