MongoDB学习之旅十二:MongoDBMapReduce

WBOY
풀어 주다: 2016-06-07 15:55:15
원래의
1204명이 탐색했습니다.

MongDB的MapReduce相当于MySQL中的group by,所以在MongoDB上使用Map/Reduce进行并行统计很容易。 使用MapReduce要实现两个函数Map函数和Reduce函数,Map函数调用emit(key,value),遍历collection中的所有记录,将key和value传递给Reduce函数进行处理。Map函

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:&#39;Tom&#39;})
> db.students.insert({classid:1, age:12, name:&#39;Jacky&#39;})
> db.students.insert({classid:2, age:16, name:&#39;Lily&#39;})
> db.students.insert({classid:2, age:9, name:&#39;Tony&#39;})
> db.students.insert({classid:2, age:19, name:&#39;Harry&#39;})
> db.students.insert({classid:2, age:13, name:&#39;Vincent&#39;})
> db.students.insert({classid:1, age:14, name:&#39;Bill&#39;})
> db.students.insert({classid:2, age:17, name:&#39;Bruce&#39;})
>
로그인 후 복사
现在我们演示如何统计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
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!