node使用 mongoose聚合 group
2018-05-24 18:27 muamaker 阅读(4230) 评论(0) 编辑 收藏 举报var mongoose = require('mongoose'); mongoose.connect("mongodb://localhost:27017/test", function(err) { if(err){ console.log('连接失败'); }else{ console.log('连接成功'); } }); var schema = new mongoose.Schema({ num:Number, name: String, size: String},{ timestamps: true }); var MyModel = mongoose.model('MyModel', schema); var group = { key: {"name":true}, cond: {}, reduce: function(doc, out) { out.count++; out.total += doc.size; }, initial: { total: 0, count: 0 }, finalize: function(out) { out.avg = out.total / out.count; } }; //这里参数数量一定要保持一致,否则会报错 MyModel.collection.group( group.key, group.cond, group.initial, group.reduce, group.finalize, true, function(err, reslut) { console.log("result====",reslut) })
使用aggregate
MyModel.aggregate([ {$match: {}}, {$group: {_id: "$name", total: {$sum: "$num"}}} ]).exec(function(err,reslut){ console.log(result) })
{$group: {_id: "$age", name:{$first:"$name"}, personCount: {$sum: 1},ageTotal:{$sum:"$age"},avgAge:{$avg:"$age"}}}
另外,mongodb 更新后