我在mongodb中有一个示例文档:
blood_group:A,
blood_category:whole blood,
num_stock:11
blood_group:B,
blood_category:whole blood,
num_stock:10
blood_group:AB,
blood_category:platelet,
num_stock:10
如何计算总计值 num_stock
具有不同的值 blood_category
,我期望这样:< / strong>
[ { blood_category: whole blood, count: 21 },
{ blood_category: platelet, count: 10 }
]
我尝试过的事情:
router.get('/blood', function(req, res) {
Blooddonation.aggregate([{$group: {_id : "$blood_category" , count :{$sum:1}}},{$sort: {_id: 1}}],function(err, blood) {
res.json({ success: true, date: blood });
});
});
使用上面的示例,得出:
[{blood_category: 'whole blood', count:2},
{blood_category: 'platelet', count:1}]
答案 0 :(得分:1)
您需要count :{$sum:"$num_stock"}
router.get('/blood', function(req, res) {
Blooddonation.aggregate([{$group: {_id : "$blood_category" , count :{$sum:"$num_stock"}}},{$sort: {_id: 1}}],function(err, blood) {
res.json({ success: true, date: blood });
});
});
样品采集
> db.xoxo.find()
{ "_id" : ObjectId("5c3d4b84d74266980e8db1bc"), "blood_group" : "A", "blood_category" : "whole blood", "num_stock" : 11 }
{ "_id" : ObjectId("5c3d4b84d74266980e8db1bd"), "blood_group" : "B", "blood_category" : "whole blood", "num_stock" : 10 }
{ "_id" : ObjectId("5c3d4b84d74266980e8db1be"), "blood_group" : "AB", "blood_category" : "platelet", "num_stock" : 10 }
结果
> db.xoxo.aggregate([{$group: {_id: "$blood_category", count : {$sum : "$num_stock"}}}])
{ "_id" : "platelet", "count" : 10 }
{ "_id" : "whole blood", "count" : 21 }
>