我有两个系列:
1.课程
1.学生
我想获取分配到相关课程对象中课程的学生的详细信息。
这是我的收藏和数据
课程:
[
{
_id: 1,
title: "Maths",
studentGroups: [
{
group: 'A',
students: [1, 5]
},
{
group: 'B',
students: [3]
}
]
},
{
_id: 2,
title: "Chemistry",
studentGroups: [
{
group: 'C',
students: [2]
},
{
group: 'B',
students: [4]
}
]
}
]
学生:
[
{
_id: 1,
name: 'Henry',
age: 15
},
{
_id: 2,
name: 'Kim',
age: 20
},
{
_id: 3,
name: 'Michel',
age: 14
},
{
_id: 4,
name: 'Max',
age: 16
},
{
_id: 5,
name: 'Nathan',
age: 19
}
]
现在我需要你的回应
[
{
_id: 1,
title: "Maths",
studentGroups: [
{
group: 'A',
students: [
{
_id: 1,
name: 'Henry',
age: 15
},
{
_id: 5,
name: 'Nathan',
age: 19
}
]
},
{
group: 'B',
students: [
{
_id: 3,
name: 'Michel',
age: 14
}
]
}
]
},
{
_id: 2,
title: "Chemistry",
studentGroups: [
{
group: 'C',
students: [
{
_id: 2,
name: 'Kim',
age: 20
}
]
},
{
group: 'B',
students: [
{
_id: 4,
name: 'Max',
age: 16
}
]
}
]
}
]
我所尝试的方法给出了正确的结果,但这不是一个好方法,我需要通过单个聚合查询来实现这一点
我的解决方案:
var courses = Courses.find({}).fetch();
courses.forEach(c => {
if (c.studentGroups && c.studentGroups.length) {
c.studentGroups.forEach(s => {
s.students = Students.find({_id: {$in: s.students}}).fetch()
})
}
})
有谁能给我推荐一个更好的单一聚合查询解决方案吗?
1条答案
按热度按时间jm81lzqq1#
首先是
$unwind
的studentGroups
,然后是students. Finally, regroup the results using
$组'中的$lookup
。Mongo Playground