我有'工作'和'用户'集合.每个用户都可以为给定的'jobCategoryId'创建一个作业,然后该作业将保存在'jobs'集合中,并包含其创建者和'jobCategoryId'的'userId'.
我正在尝试将这两个集合组合在一起,因此当我获取作业时,我将拥有所有用户数据的"用户"字段,而不是该作业的"userId"字段.这就是我现在这样做的方式:
Job.aggregate([{
$match: {
jobCategoryId: mongoose.Types.ObjectId(jobCategoryId)
}
}, {
$lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'user'
}
}, {
$project: {
_id: 1,
description: 1,
title: 1,
user: { $arrayElemAt: ['$user', 0] }
}
}, {
$project: {
_id: 1,
title: 1,
description: 1,
'user.name': '$user.name'
}
}])
Run Code Online (Sandbox Code Playgroud)
返回以下内容:
[{
_id: 'some id',
title: 'title',
description: 'description',
user: {
name: 'Mike'
}
}]
Run Code Online (Sandbox Code Playgroud)
结果是正确的但我真的很感兴趣,如果有任何其他方法在使用$ arrayElemAt时直接保留用户对象的某些字段,或者我注定要在管道中使用2个投影?有谁可以帮我解决这个小问题?我真的很感激.