请帮助我加入MongoDB 3.4中的多个集合
school_collection:
{
"_id" : ObjectId("5f9934b952255731e8dbfa17"),
class:[]
}
class_collection:
{
"_id" : ObjectId("5f9a4398e146b6327457967b"),
"school_id" : ObjectId("5f9934b952255731e8dbfa17"),
"name" : "",
"description" : ""
students:[]
}
students_collection:
{
"_id" : ObjectId("5f9a4398e146b6327457967c"),
"class_id" : ObjectId("5f9a4398e146b6327457967b"),
"name" : "",
"description" : ""
}
预期结果:
{
"_id" : "5f9934b952255731e8dbfa17",
class: [
{
"_id": "5f9a4398e146b6327457967b",
"name": "",
"description": ""
students: [
{
"_id" : "5f9a4398e146b6327457967c",
"name" : "",
"description" : ""
}
]
}
]
}
我可以使用$lookup
来收集课程信息,但是如何在每个课程中获取学生详细信息数组?
dbConnection.db().collection(db_collections.SCHOOL).aggregate([
{
$lookup: {
from: db_collections.CLASS,
localField: "_id",
foreignField: "class_id",
as: "class"
}
}])
答案 0 :(得分:1)
MongoDB 3.4
$lookup
加入课程集合$lookup
加入学生收藏集$addFields
更新班级字段,$map
更新班级数组循环并从学生数组中获取学生,$filter
获取匹配的学生并返回学生字段db.school.aggregate([
{
$lookup: {
from: "class",
localField: "_id",
foreignField: "school_id",
as: "class"
}
},
{
$lookup: {
from: "students",
localField: "class._id",
foreignField: "class_id",
as: "students"
}
},
{
$addFields: {
class: {
$map: {
input: "$class",
as: "c",
in: {
_id: "$$c._id",
school_id: "$$c.school_id",
name: "$$c.name",
description: "$$c.description",
students: {
$filter: {
input: "$students",
cond: { $eq: ["$$c._id", "$$this.class_id"] }
}
}
}
}
}
}
},
{ $project: { students: 0 } }
])