当前位置:Gxlcms > 数据库问题 > mongodb MapReduce

mongodb MapReduce

时间:2021-07-01 10:21:17 帮助过:11人阅读

计算每个客户的总消费

执行过程:

技术分享

1. 执行 map 操作过程

  • 定义 map (映射) 函数来处理每个文档:
  • 映射每个文档的cust_id, 并处理 items
  • 先遍历 items,分别对每个items成员 qtyprice相乘再求总和
var mapFunction2 = function() {
                       var key = this.cust_id;
                       var value = 0;
                       for (var idx = 0; idx < this.items.length; idx++) {
                            value += this.items[idx].qty * this.items[idx].price;
                       }
                       emit(key, value);
                    };

2. 定义reduce 函数有两个参数 keyCustId 和 valuesPrices

  • valuesPrices 是数组,由 keyCustId 分组, 收集 value 而来
  • reduces 函数 对 valuesPrices 数组 求和.
var reduceFunction2 = function(keyCustId, valuesPrices) {
                     return Array.sum(valuesPrices);
                  };

3. 执行 map-reduce 函数

db.orders.mapReduce(
                     mapFunction2,
                     reduceFunction2,
                     { out: "map_reduce_example" }
                   )

mongodb MapReduce

标签:key   定义   out   limit   var   value   item   nbsp   oct   

人气教程排行