我有如下数据:
db.Items = [{
_id: 1,
dataa: [{'a': 1, userId: 1}, {'a': 2, userId: 2}],
datab: [{'b': 1, userId: 2}, {'b': 2, userId: 3}]
}]
和
db.Users = [{
_id: 1,
username: 'one',
picture: 'picone',
email: 'emailone'
}, {
_id: 2,
username: 'two',
picture: 'pictwo',
email: 'emailtwo'
}, {
_id: 3,
email: 'emailthree'
}]
我想要一个mongodb查询,该查询返回db.Items集合,其中userId值替换为相应的Users集合中的用户名和图片:
DesiredResult = [{
_id: 1,
dataa: [{'a': 1, user: {username: 'one', picture: 'picone'}},
{'a': 2, user: {username: 'two', picture: 'pictwo'}}],
datab: [{'b': 1, user: {username: 'two', picture: 'pictwo'}},
{'b': 2, user: {}}]
}]
似乎它应该是一个汇总的$ lookup值,但我无法使其正常工作。 userId = 3的用户对象可以为null或其他某个值,以表示它缺少这些值。
更多信息以显示这与标记为重复的问题不同:
我可以通过以下方式从用户集合中获取总计的$ lookup以返回所需的值:
db.Items.aggregate([{$match: {_id: 1}},
{$lookup: { from: 'Users',
localField: 'dataa.userId',
foreignField: '_id',
as: 'dataaUsers' }},
{$lookup: { from: 'Users',
localField: 'datab.userId',
foreignField: '_id',
as: 'databUsers' }}])
到目前为止,我有:
PartialResult = [{
_id: 1,
dataa: [{'a': 1, userId: 1}, {'a': 2, userId: 2}],
datab: [{'b': 1, userId: 2}, {'b': 2, userId: 3}],
dataaUsers: [{
_id: 1,
username: 'one',
picture: 'picone',
email: 'emailone'
}, {
_id: 2,
username: 'two',
picture: 'pictwo',
email: 'emailtwo'
}],
databUsers: [{
_id: 2,
username: 'two',
picture: 'pictwo',
email: 'emailtwo'
}, {
_id: 3,
email: 'emailthree'
}]
但是我无法正确地 $project
转换成上面 DesiredResult
的格式。我认为与大多数$ project阶段不同的是,它需要访问似乎无效的对象元素数组。