我正在尝试对users
集合进行汇总,而不是对另一个集合$lookup
进行usersurveystatuses
来查找该用户是否已完成调查。这可以正常工作,但它仅投影具有匹配调查的用户。即使调查无关,我如何保留所有用户。
代码:
db.collection('users')
.aggregate([
{
$match: { roles: { $in: ['user'] } },
},
{
$lookup: {
from: 'usersurveystatuses',
localField: '_id',
foreignField: 'user_id',
as: 'completedSurveys',
},
},
{
$unwind: {
path: '$completedSurveys',
},
},
{
$match: {
'completedSurveys.status': 'completed',
},
},
{
$group: {
_id: '$_id',
name: { $first: '$firstname' },
surname: { $first: '$lastname' },
credits: { $first: '$credits' },
completedSurveys: { $push: '$completedSurveys' },
},
},
{
$project: {
_id: 1,
name: 1,
surname: 1,
credits: 1,
completedSurveys: 1,
},
},
])
.toArray()
.then(users => {
console.log(users)
})
结果仅返回已完成调查的用户。
[ { _id: 5be98fa0b02eed1b2a17ca54,
name: 'User',
surname: 'User',
credits: 0,
completedSurveys: [ [Object], [Object] ] } ]