如何在MongoDB 3.4中加入多个集合?

时间:2020-10-29 06:01:32

标签: mongodb mongodb-query

请帮助我加入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"
    }
}])

1 个答案:

答案 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 } }
])

Playground