服务器之家

服务器之家 > 正文

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

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

group参数选项:

1.key: 这个就是分组的key
2.initial: 每组都分享一个初始化函数,特别注意:是每一组initial函数。
3.reduce: 这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象。有多少个文档, $reduce就会调用多少次。
4.condition: 这个就是过滤条件。
5.finalize: 这是个函数,每一组文档执行完后,多会触发此方法。

标签:

相关文章

热门资讯

沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
和平精英超高音质怎么修改 和平精英超高音质重启设置方法
和平精英超高音质怎么修改 和平精英超高音质重启设置方法 2019-06-26
返回顶部