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

发布时间:2022-04-21 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了MongoDB学习笔记之分组(group)使用示例脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
// 准备测试数据
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 &#63; '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: 这是个函数,每一组文档执行完后,多会触发此方法。

脚本宝典总结

以上是脚本宝典为你收集整理的MongoDB学习笔记之分组(group)使用示例全部内容,希望文章能够帮你解决MongoDB学习笔记之分组(group)使用示例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。