MongoDB: How to populate the nested object with lookup query? MongoDB: How to populate the nested object with lookup query? mongoose mongoose

MongoDB: How to populate the nested object with lookup query?


  • $unwind deconstruct recipients array
  • $lookup with users collection for recipients.userId
  • $unwind deconstruct recipients.userId array
  • $lookup with users collection for sender
  • $unwind deconstruct sender array
  • $group by _id and reconstruct recipients array
db.mails.aggregate([  { $unwind: "$recipients" },  {    $lookup: {      from: "users",      localField: "recipients.userId",      foreignField: "_id",      as: "recipients.userId"    }  },  { $unwind: "$recipients.userId" },  {    $lookup: {      from: "users",      localField: "sender",      foreignField: "_id",      as: "sender"    }  },  { $unwind: "$sender" },  {    $group: {      _id: "$_id",      recipients: { $push: "$recipients" },      subject: { $first: "$subject" },      body: { $first: "$body" },      sender: { $first: "$sender" }    }  }])

Playground


Try This:

db.emails.aggregate([    { $unwind: "$recipients" },    {        $lookup: {            from: "users",            let: { userId: "$recipients.userId", status: "$recipients.stutus" },            pipeline: [                {                    $match: {                        $expr: { $eq: ["$_id", "$$userId"] }                    }                },                {                    $project: {                        "_id": 0,                        "userId": {                            "firstName": "$firstName",                            "lastName": "$lastName",                        },                        "status": "$$status"                    }                }            ],            as: "recipient"        }    },    {        $lookup: {            from: "users",            let: { userId: "$sender" },            pipeline: [                {                    $match: {                        $expr: { $eq: ["$_id", "$$userId"] }                    }                },                {                    $project: {                        "_id": 0,                        "firstName": 1,                        "lastName": 1                    }                }            ],            as: "sender"        }    },    {        $group: {            _id: "$_id",            subject: { $first: "$subject" },            body: { $first: "$body" },            recipients: { $push: { $arrayElemAt: ["$recipient", 0] } },            sender: { $first: { $arrayElemAt: ["$sender", 0] } }        }    }]);