我有一个 JobApplication 集合,其中包含一个求职者参考,如下所示:
_id | job_post | 求职者 |
---|---|---|
60b62fcf36c4bd19fc2a1733 | 60a59ca4b43549049baef311 | 60802ba5be283f6ffcf07821 |
我想找到按国家分组的求职者数量
我试着这样做:
return await JobApplication.aggregate([
{
$lookup: {
from: Jobseeker.collection.collectionName,
localField: 'jobseeker',
foreignField: '_id',
as: 'jobseeker'
}
},
{
$unwind: '$jobseeker'
},
{
$group: {
_id: "$jobseeker.current_country_of_residence",
count: { $sum: 1 }
}
}
])
但是我得到了这样的重复数据:
"applicants_by_locations": [
{
"_id": "606f4d2bbca7c6f2be0625f9",
"count": 1
},
{
"_id": "606f4d2bbca7c6f2be0625f9",
"count": 2
}]
我得到了两次相同的国家/地区 _id,而不是一个 _id,计数为 3。
我不确定这里发生了什么!!
更新代码:
await JobApplication.aggregate([
{
$lookup: {
from: Jobseeker.collection.collectionName,
localField: 'jobseeker',
foreignField: '_id',
as: 'jobseeker'
} },
{ $unwind: '$jobseeker' },
{ $group: {
_id: "$jobseeker.current_country_of_residence",
count: { $sum: 1 }
} },
{
$group: {
_id: "$_id",
count: { $sum: "$count" }
} }
])