MongoDB - lookup - multiple collection - Result in one array MongoDB - lookup - multiple collection - Result in one array mongoose mongoose

MongoDB - lookup - multiple collection - Result in one array


You can try lookup with pipeline,

  • $lookup with nodes and pass siteId to pipeline
  • $match siteId condition
  • $lookup with devices and pass deviceId to pipeline
  • $match deviceId condition
  • $lookup with sensors collection
db.sites.aggregate([  {    $lookup: {      from: "nodes",      let: { siteId: "$_id" },      pipeline: [        { $match: { $expr: { $eq: ["$$siteId", "$siteId"] } } },        {          $lookup: {            from: "devices",            let: { nodeId: "$_id" },            pipeline: [              { $match: { $expr: { $eq: ["$$nodeId", "$nodeId"] } } },              {                $lookup: {                  from: "sensors",                  localField: "_id",                  foreignField: "deviceId",                  as: "sensors"                }              }            ],            as: "devices"          }        }      ],      as: "nodes"    }  }])

Playground