db.coll.group( {key: { a:true, b:true },
cond: { active:1 },
reduce:function(obj,prev){prev.csum+=obj.c; },
initial: {csum: 0 }
});
参数解释:
query是很常用的,它用来在map阶段过滤查询条件的以限定MapReduce操作的记录范围,sort和limit集合query使用。
out指定输出结果的collections名称
Keeptemp布尔型,默认是false,如果是true那么生成的collection是永久存在的,如果是false,那么在客户端连接关闭后,会自动删除生成的collection
Finalize一般用来计算平均数,裁剪数组,清除多余信息
query是很常用的,它用来在map阶段过滤查询条件的以限定MapReduce操作的记录范围,sort和limit集合query使用。
out指定输出结果的collections名称
Keeptemp布尔型,默认是false,如果是true那么生成的collection是永久存在的,如果是false,那么在客户端连接关闭后,会自动删除生成的collection
Finalize一般用来计算平均数,裁剪数组,清除多余信息
{ result : <collection_name>,
counts : {
input : <number of objects scanned>,
emit : <number of times emit was called>,
output : <number of items in output collection>
} ,
timeMillis : <job_time>,
ok : <1_if_ok>,
[, err : <errmsg_if_error>]
}
result:储存结果的collection的名字
input:满足条件的数据行数
emit:emit调用次数,也就是所有集合中的数据总量
ouput:返回结果条数
timeMillis:执行时间,毫秒为单位
ok:是否成功,成功为1
err:如果失败,这里可以有失败原因
给出官方文档的一个例子:
$ ./mongo
> db.things.insert( { _id : 1, tags : ['dog', 'cat'] } );
> db.things.insert( { _id : 2, tags : ['cat'] } );
> db.things.insert( { _id : 3, tags : ['mouse', 'cat', 'dog'] } );
> db.things.insert( { _id : 4, tags : [] } );
> // map function
> m = function(){
... this.tags.forEach(
... function(z){
... emit( z , { count : 1 } );
... }
... );
...};
> // reduce function
> r = function( key , values ){
... var total = 0;
... for ( var i=0; i<values.length; i++ )
... total += values[i].count;
... return { count : total };
...};
> res = db.things.mapReduce(m,r);
> res
{"timeMillis.emit" : 9 , "result" : "mr.things.1254430454.3" ,
"numObjects" : 4 , "timeMillis" : 9 , "errmsg" : "" , "ok" : 0}
> db[res.result].find()
{"_id" : "cat" , "value" : {"count" : 3}}
{"_id" : "dog" , "value" : {"count" : 2}}
{"_id" : "mouse" , "value" : {"count" : 1}}
> db[res.result].drop()