如何在猫鼬聚合中使用字段值?
我尝试了最新版本的mongodb mongoose。
Group.find({name:'1'},function(err,groups){
groups.forEach(function(g){
result=await People.countDocuments({group:g._id})
});
});
我已经检查过此代码的“结果”是3、5、2
我要使用汇总
Group.aggregate()
.project({_id:true,name:true})
.addFields({numOfPeople: await People.countDocuments({group:this._id})});
输出
[{name:'1',numOfPeople:0},
{name:'2',numOfPeople:0},
{name:'3',numOfPeople:0}]
预期
[{name:'1',numOfPeople:3},
{name:'2',numOfPeople:5},
{name:'3',numOfPeople:2}]
答案 0 :(得分:0)
您必须使用分组依据
db.groups.aggregate(
[
{
$group : {
_id : "$name",
numOfPeople: { $sum: 1 }
}
}
]
);