MongDB的MapReduce相当于MySQL中的“group by”,所以在MongoDB上使用Map/Reduce进行并行“统计”很容易。

使用MapReduce要实现两个函数Map函数和Reduce函数,Map函数调用emit(key,value),遍历collection中的所有记录,将key和value传递给Reduce函数进行处理。Map函数和Reduce函数可以使用JS来实现,可以通过db.runCommand或mapReduce命令来执行一个MapReduce操作。

示例shell

db.runCommand(
{ mapreduce : <collection>,
map : <mapfunction>,
reduce : <reducefunction>
[, query : <query filter object>]
[, sort : <sorts the input objects using this key. Useful for optimization, like sorting by the
emit key for fewer reduces>]
[, limit : <number of objects to return from collection>]
[, out : <see output options below>]
[, keeptemp: <true|false>]
[, finalize : <finalizefunction>]
[, scope : <object where fields go into javascript global scope >]
[, verbose : true]
}
);

参数说明:
     mapreduce: 要操作的目标集合。
    map: 映射函数 (生成键值对序列,作为 reduce 函数参数)。
     reduce: 统计函数。
     query: 目标记录过滤。
     sort: 目标记录排序。
     limit: 限制目标记录数量。
     out: 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。
    keeptemp: 是否保留临时集合。
     finalize: 最终处理函数 (对 reduce 返回结果进行最终整理后存入结果集合)。
     scope: 向 map、reduce、finalize 导入外部变量。
     verbose: 显示详细的时间统计信息。

下面我们准备数据以备后面示例所需

> db.students.insert({classid:1, age:14, name:'Tom'})
> db.students.insert({classid:1, age:12, name:'Jacky'})
> db.students.insert({classid:2, age:16, name:'Lily'})
> db.students.insert({classid:2, age:9, name:'Tony'})
> db.students.insert({classid:2, age:19, name:'Harry'})
> db.students.insert({classid:2, age:13, name:'Vincent'})
> db.students.insert({classid:1, age:14, name:'Bill'})
> db.students.insert({classid:2, age:17, name:'Bruce'})
>

现在我们演示如何统计1班和2班的学生数量

Map 函数必须调用 emit(key, value) 返回键值对,使用 this 访问当前待处理的 Document。

这里this一定不能忘了!!!

> m = function() { emit(this.classid, 1) }
function () {
emit(this.classid, 1);
}
>

value 可以使用 JSON Object 传递 (支持多个属性值)。例如:
    emit(this.classid, {count:1})
    Reduce 函数接收的参数类似 Group 效果,将 Map 返回的键值序列组合成 { key, [value1,value2, value3, value...] } 传递给 reduce。

> r = function(key, values) {
... var x = 0;
... values.forEach(function(v) { x += v });
... return x;
... }
function (key, values) {
var x = 0;
values.forEach(function (v) {x += v;});
return x;
}
>

Reduce 函数对这些 values 进行 "统计" 操作,返回结果可以使用 JSON Object。

结果如下:

> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res"
... });
{
"result" : "students_res",
"timeMillis" : 1587,
"counts" : {
"input" : 8,
"emit" : 8,
"output" : 2
},
"ok" : 1
}
> db.students_res.find()
{ "_id" : 1, "value" : 3 }
{ "_id" : 2, "value" : 5 }
>

mapReduce() 将结果存储在 "students_res" 表中。

利用 finalize() 我们可以对 reduce() 的结果做进一步处理。

> f = function(key, value) { return {classid:key, count:value}; }
function (key, value) {
return {classid:key, count:value};
}
>

我们再重新计算一次,看看返回的结果:

> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res",
... finalize:f
... });
{
"result" : "students_res",
"timeMillis" : 804,
"counts" : {
"input" : 8,
"emit" : 8,
"output" : 2
},
"ok" : 1
}
> db.students_res.find()
{ "_id" : 1, "value" : { "classid" : 1, "count" : 3 } }
{ "_id" : 2, "value" : { "classid" : 2, "count" : 5 } }
>

列名变与 “classid”和”count”了,这样的列表更容易理解。

我们还可以添加更多的控制细节。

> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res",
... finalize:f,
... query:{age:{$lt:10}}
... });
{
"result" : "students_res",
"timeMillis" : 358,
"counts" : {
"input" : 1,
"emit" : 1,
"output" : 1
},
"ok" : 1
}
> db.students_res.find();
{ "_id" : 2, "value" : { "classid" : 2, "count" : 1 } }
>

可以看到先进行了过滤,只取age<10 的数据,然后再进行统计,所以就没有1 班的统计数据了。

MongoDB整理笔记のMapReduce的更多相关文章

  1. MongoDB整理笔记の走进MongoDB世界

    本人学习mongodb时间不长,但是鉴于工作的需要以及未来发展的趋势,本人想更深层的认识mongodb底层的原理以及更灵活的应用mongodb,边学边工作实践.  mongodb属于nosql中算是最 ...

  2. MongoDB整理笔记のjava MongoDB分页优化

    最近项目在做网站用户数据新访客统计,数据存储在MongoDB中,统计的数据其实也并不是很大,1000W上下,但是公司只配给我4G内存的电脑,让我程序跑起来气喘吁吁...很是疲惫不堪. 最常见的问题莫过 ...

  3. MongoDB整理笔记のID自增长

    以下是官网原文地址: http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ 概要 MongoDB 的_i ...

  4. MongoDB整理笔记のReplica Sets + Sharding

    MongoDB Auto-Sharding 解决了海量存储和动态扩容的问题,但离实际生产环境所需的高可靠.高可用还有些距离,所以有了"Replica Sets + Sharding" ...

  5. MongoDB整理笔记の新增Shard Server

    1.启动一个新Shard Server 进程 [root@localhost ~]# mkdir /data/shard/s2 [root@localhost ~]# /Apps/mongo/bin/ ...

  6. MongoDB整理笔记のSharding分片

    这是一种将海量的数据水平扩展的数据库集群系统,数据分表存储在sharding 的各个节点上,使用者通过简单的配置就可以很方便地构建一个分布式MongoDB 集群.MongoDB 的数据分块称为 chu ...

  7. MongoDB整理笔记の增加节点

    MongoDB Replica Sets 不仅提供高可用性的解决方案,它也同时提供负载均衡的解决方案,增减Replica Sets 节点在实际应用中非常普遍,例如当应用的读压力暴增时,3 台节点的环境 ...

  8. MongoDB整理笔记の管理Replica Sets

    一.读写分离 从库能进行查询,这样可以分担主库的大量的查询请求.   1.先向主库中插入一条测试数据 [root@localhost bin]# ./mongo --port 28010 MongoD ...

  9. MongoDB整理笔记のReplica oplog

    主从操作日志oplog MongoDB的Replica Set架构是通过一个日志来存储写操作的,这个日志就叫做"oplog".oplog.rs是一个固定长度的capped coll ...

随机推荐

  1. Linux 简单字符设备驱动

    1.hello_drv.c (1) 初始化和卸载函数的格式是固定的,函数名自定义 (2) printk是内核的打印函数,用法与printf一致 (3) MODULE_LICENSE:模块代码支持开源协 ...

  2. Verilog-2001新增特性

    l generate语句 Verilog-2001添加了generate循环,允许产生 module和primitive的多个实例化,同时也可以产生多个variable,net,task,functi ...

  3. 解决Maven提示:Could not read settings.xml, assuming default values

    本文转载自:http://blog.csdn.net/hqocshheqing/article/details/47702049 最近在学习Maven  时总是出现 Could not read se ...

  4. 1074 Reversing Linked List

    题意: 每k个元素反转链表,不足k个就不反转.如原链表为1→2→3→4→5→6,k=3,则反转后的链表为3→2→1→6→5→4:若k=4,则反转后的链表为4→3→2→1→5→6. 思路: 这题会比较烦 ...

  5. Build Assetbundle出错:An asset is marked as dont save, but is included in the build

    前天Build Assetbundle的时候出错了,导致打包失败,具体日志内容如下: An asset is marked as dont save, but is included in the b ...

  6. WebSocket实战之JavaScript例子

    一.详细代码案例 详细解读一个简单html5 WebSocket的Js实例教程,附带完整的javascript websocket实例源码,以及实例代码效果演示页面,并对本实例的核心代码进行了深入解读 ...

  7. Springboot项目打成jar包运行 和 打成war包 外部tomcat运行

    Jar打包方式运行 类型为jar时 <packaging>jar</packaging> 1.使用命令mvn clean  package 打包 2.使用java –jar 包 ...

  8. ClientDataSet1.LoadFromStream

    lStream3.Position := 0;        lDataSet.LoadFromStream(lStream3);

  9. Mycat实战之离散分片

    1 枚举分片(customer表) #### 1.1 修改配置信息加载配置文件 datanode hash-int vi partition-hash-int.txt db1=0 db2=1 [roo ...

  10. VS编译常见错误枚举01

    fatal error C1189: #error :  This file requires _WIN32_WINNT to be #defined at least to 0x0403. Valu ...