how can i join multiple collections in mongodb?

MongoDB 3.4

  • $lookup join class collection
  • $lookup join students collection
  • $addFields to update class field, $map to iterate loop of class array and get students from students array, $filter to get matching students and return in students field
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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top