I'm trying to join my members collection with a email collection, which works. But it is showing an array of email objects and I only need an array email addresses. The email address is a field of the email collection. A member can have multiple email addresses. The result should show all the fields from the member collection plus the additional address field.
Members collection
_id: 62692f3503ed123e35a56a12
name: "John",
lastName: "Cena",
// arbitrary number of fields
Emails Collection
_id: 74331a2663ed999e35a33a09
memberId: 62692f3503ed123e35a56a12,
email: "[email protected]"
I tried
db.members.aggregate([{"$lookup" : {from: "emails",localField: "_id",foreignField: "memberId",as: "emails"},
Result
_id: 62692f3503ed123e35a56a12
name: "John",
lastName: "Cena",
emails: [
{
_id:
memberId: 62692f3503ed123e35a56a12,
email: "[email protected]"
},
{...}
]
What I need
_id: 62692f3503ed123e35a56a12
name: "John",
lastName: "Cena",
emails: ["[email protected]", "..."]
// any other fields
How can I do that?
CodePudding user response:
You can use $map as part of $addFields stage to convert $lookup
result:
db.members.aggregate([
{
"$lookup" : {
from: "emails",
localField: "_id",
foreignField: "memberId",
as: "emails"}
},
{
$addFields: {
emails: { $map: { input: "$emails", as: "$$this.email" } }
}
}
]);