标签:key 定义 out limit var value item nbsp oct
MapReduce 命令
以下是MapReduce的基本语法:
>db.collection.mapReduce(
function() {emit(key,value);}, //map 函数
function(key,values) {return reduceFunction}, //reduce 函数
{
out: collection,
query: document,
sort: document,
limit: number
}
)
使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数,Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将key与 value 传递给 Reduce 函数进行处理。
Map 函数必须调用 emit(key, value) 返回键值对。
参数说明:
现有集合 orders 内容如下
db.orders.insert([
{
_id: 1,
cust_id: "marong",
ord_date: new Date("Oct 04, 2012"),
status: ‘A‘,
items: [ { sku: "mmm", qty: 5, price: 2.5 },
{ sku: "nnn", qty: 5, price: 2.5 } ]
},
{
_id: 2,
cust_id: "marong",
ord_date: new Date("Oct 05, 2012"),
status: ‘B‘,
items: [ { sku: "mmm", qty: 5, price: 3 },
{ sku: "nnn", qty: 5, price: 3 } ]
}
])
执行过程:
map (映射) 函数来处理每个文档:cust_id, 并处理 itemsitems,分别对每个items成员 qty和price相乘再求总和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);
};
valuesPrices 是数组,由 keyCustId 分组, 收集 value 而来reduces 函数 对 valuesPrices 数组 求和.var reduceFunction2 = function(keyCustId, valuesPrices) {
return Array.sum(valuesPrices);
};
db.orders.mapReduce(
mapFunction2,
reduceFunction2,
{ out: "map_reduce_example" }
)标签:key 定义 out limit var value item nbsp oct
原文地址:http://www.cnblogs.com/Erick-L/p/7245982.html