MongoDB: How to populate the nested object with lookup query?
$unwind
deconstructrecipients
array$lookup
with users collection forrecipients.userId
$unwind
deconstructrecipients.userId
array$lookup
with users collection forsender
$unwind
deconstructsender
array$group
by_id
and reconstructrecipients
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" } } }])
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] } } } }]);