首页 > 数据库 > MongoDB > 正文

MongoDB学习笔记之分组(group)使用示例

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

这篇文章主要介绍了MongoDB学习笔记之分组(group)使用示例,本文直接给出一组测试数据,然后练习分组的基本使用,需要的朋友可以参考下

 

 
  1. // 准备测试数据 
  2. db.user.drop(); 
  3. for(var i=10; i< 100; i++) { 
  4. db.user.insert({ 
  5. name:"user" + i,  
  6. age : Math.floor(Math.random()*10)+ 20,  
  7. sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F', 
  8. chinese : Math.floor(Math.random()*50)+50, 
  9. math : Math.floor(Math.random()*50)+50, 
  10. english : Math.floor(Math.random()*50)+50, 
  11. class : "C" + i%5 
  12. }) 
  13. } 
  14.  
  15. // group函数 
  16. // 按照class进行分组,显示每个class中的用户姓名和性别 
  17. db.user.group({ 
  18. key: {"class": true}, 
  19. initial: {"person": []}, 
  20. reduce: function(cur, prev) { 
  21. prev.person.push({name: cur.name, sex: cur.sex, age: cur.age}); 
  22. } 
  23. }); 
  24.  
  25. // 对age>25的用户,按照class进行分组,显示每个class中的用户姓名和性别,并统计每组的人数 
  26. db.user.group({ 
  27. key: {"class": true}, 
  28. initial: {"person": []}, 
  29. reduce: function(doc, out){ 
  30. out.person.push({name: doc.name, sex: doc.sex, age: doc.age}); 
  31. }, 
  32. finalize: function(out){ 
  33. out.count = out.person.length; 
  34. }, 
  35. condition: {"age": {$gt: 25}} 
  36. }) 
  37.  
  38. // 分组计算每个class中,chinese最大值和最小值 
  39. db.user.group({ 
  40. key: {"class": true}, 
  41. initial: {"chinese_min": 0, "chinese_max":0 }, 
  42. reduce: function(doc, out){ 
  43. out.chinese_min = doc.chinese; 
  44. out.chinese_min = doc.chinese; 
  45.  
  46. out.chinese_min = Math.min(out.chinese_min, doc.chinese); 
  47. out.chinese_max = Math.max(out.chinese_max, doc.chinese) 
  48. }, 
  49. }) 
  50.  
  51. // 利用分组,计算每个总成绩和成绩平均值 
  52. db.user.group({ 
  53. key: {"_id" : true}, 
  54. initial: {name:"", total: 0, avg: 0}, 
  55. reduce: function(doc, out){ 
  56. out.name = doc.name; 
  57. out.total = doc.chinese + doc.math + doc.english; 
  58. out.avg = Math.floor(out.total / 3); 
  59. } 
  60. }) 

group参数选项:

1.key: 这个就是分组的key

2.initial: 每组都分享一个初始化函数,特别注意:是每一组initial函数。

3.reduce: 这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象。有多少个文档, $reduce就会调用多少次。

4.condition: 这个就是过滤条件。

5.finalize: 这是个函数,每一组文档执行完后,多会触发此方法。

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