mongoDB汇总查找每个州的雇员组总数

时间:2019-01-20 23:20:46

标签: database mongodb

使用汇总查找各州的雇员总数 我在下面的屏幕快照链接中尝试了以下操作。但是结果是0。

enter image description here

db.research.aggregate({$unwind:'$offices'},{"$match": 
{'offices.country_code':"USA"}},{"$project": {'offices.state_code' : 1}}, 
{"$group" : {"_id":'$of
fices.state_code',"count" : {"$sum":'$number_of_employees'}}})

1 个答案:

答案 0 :(得分:0)

您需要$project number_of_employees才能进行下一阶段的计数,也可以删除$project阶段

db.research.aggregate([
    {$unwind:'$offices'},
    {"$match": {'offices.country_code':"USA"}},
    {"$project": {'offices.state_code' : 1, 'number_of_employees' : 1}}, //project number_of_employees
    {"$group" : {"_id":'$offices.state_code',"count" : {"$sum":'$number_of_employees'}}}
])

db.research.aggregate([
    {$unwind:'$offices'},
    {"$match": {'offices.country_code':"USA"}},
    {"$group" : {"_id":'$offices.state_code',"count" : {"$sum":'$number_of_employees'}}}
])