Perform $lookup with object value in array from pipeline Perform $lookup with object value in array from pipeline mongoose mongoose

Perform $lookup with object value in array from pipeline


You can put $lookup stage inside pipeline,

  • $lookup with users collection
  • $addFields, $arrayElemAt to get first element from above user lookup result
Property.aggregate([  { $match: { _id: ObjectId(propertyId) } },  {    $lookup: {      from: "propertytestimonials",      let: { propPropertyId: "$_id" },      pipeline: [        {          $match: {            $expr: { $eq: ["$propertyId", "$$propPropertyId"] }          }        },        {          $lookup: {            from: "users",            localField: "userId",            foreignField: "_id",            as: "user"          }        },        {          $addFields: {            user: { $arrayElemAt: ["$user", 0] }          }        }      ],      as: "testimonials"    }  }])

Playground