MongoDB学习笔记--分组(1)

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 ? '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参数选项:
  • key: 这个就是分组的key
  • initial: 每组都分享一个初始化函数,特别注意:是每一组initial函数。
  • reduce: 这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象。有多少个文档, $reduce就会调用多少次。
  • condition: 这个就是过滤条件。
  • finalize: 这是个函数,每一组文档执行完后,多会触发此方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值