首页 > 数据库 > MongoDB > 正文

MongoDB学习笔记之MapReduce使用示例

2020-03-14 13:21:19
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了MongoDB学习笔记之MapReduce使用示例,本文直接给出实例代码,需要的朋友可以参考下

一、mapreduce是根据map函数里调用的emit函数的第一个参数来进行分组的

Map-Reduce是一种计算模型,简单的说就是将大批量的工作(数据)分解(MAP)执行,然后再将结果合并成最终结果(REDUCE)。

使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数, Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将key 与 value 传递给 Reduce 函数进行处理。Map 函数必须调用 emit(key, value) 返回键值对。

参数说明:

1. map :映射函数 (生成键值对序列,作为 reduce 函数参数)。

2. reduce 统计函数,reduce函数的任务就是将key- values变成key-value,也就是把values数组变成一个单一的值value。

3. out 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。

4. query 一个筛选条件,只有满足条件的文档才会调用map函数。(query。limit,sort可以随意组合)

5. sort 和limit结合的sort排序参数(也是在发往map函数前给文档排序),可以优化分组机制

6. limit 发往map函数的文档数量的上限(要是没有limit,单独使用sort的用处不大)

 

 
  1. //测试数据准备 
  2. db.user.drop(); 
  3.  
  4. for(var i=10; i< 100; i++) { 
  5. db.user.insert({ 
  6. name:"user" + i,  
  7. age : Math.floor(Math.random()*10)+ 20,  
  8. sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F', 
  9. chinese : Math.floor(Math.random()*50)+50, 
  10. math : Math.floor(Math.random()*50)+50, 
  11. english : Math.floor(Math.random()*50)+50, 
  12. class : "C" + i%5 
  13. }) 
  14. } 
  15.  
  16.  
  17. // runCommand运行方式 
  18. db.sales.runCommand({ 
  19. mapreduce: "user", 
  20.  
  21. map: function(){ 
  22. if(this.class == "C1") { 
  23. emit(this.age, this.age); 
  24. } 
  25. }, 
  26.  
  27. reduce: function(key,values){ 
  28. var maxValue = Max(key, values); 
  29. return maxValue; 
  30. }, 
  31.  
  32. { 
  33. out: {inline: 1}, 
  34. query : "", 
  35. sort: "", 
  36. limit: "", 
  37. } 
  38. }) 
  39.  
  40.  
  41. db.user.mapReduce( 
  42. // 映射函数,里面会调用emit(key,value),集合会按照你指定的key进行映射分组。 
  43. function(){ 
  44. // 按照emit函数的第一个参数进行分组 
  45. // 第二个参数的值会传递给reduce 
  46. emit(this.age, this);  
  47. }, 
  48.  
  49. // 简化函数,会对map分组后的数据进行分组简化 
  50. // 在reduce(key,value)中的key就是emit中的key, vlaues为emit分组后的emit(value)的集合 
  51. function(key, values){ 
  52. var maxValue = Math.max(key, values); 
  53. return maxValue; 
  54. }, 
  55.  
  56. // 可选参数 
  57. { 
  58. query: {sex: "F"}, 
  59. out: "result", 
  60. sort : {}, 
  61. limit : 0 
  62. } 
  63. ) 

执行结果:

 

 
  1. { 
  2. "result" : "result", // 存放的集合名 
  3. "timeMillis" : 23, 
  4. "counts" : { 
  5. "input" : 29, // 传入文档的个数 
  6. "emit" : 29, // 此函数被调用的次数 
  7. "reduce" : 6, // 此函数被调用的次数 
  8. "output" : 8 // 最后返回文档的个数 
  9. }, 
  10. "ok" : 1 
  11. } 

查看返回的结果:

 

 
  1. db.result.find() 
 

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表