Je moet $unwind
om de buitenlandse _ids van zowel scalair als subdocument af te vlakken en $group
. toe te voegen fase aan het einde van de pijplijn om de oorspronkelijke structuur terug te krijgen.
$first
accumulator om de velden en $push
. te behouden met $arrayElemAt
om de arraywaarden te verzamelen om aan te passen voor $unwind
var linkedModels = [
{
"$match": { "del": false }
},
{
"$lookup": {
from: "charnpcalign",
localField: "align",
foreignField: "_id",
as: "linked_align"
}
},
{
"$unwind":"$classes"
},
{
"$lookup": {
from: "charnpcclass",
localField: "classes",
foreignField: "_id",
as: "linked_classes"
}
},
{
"$group": {
"_id": "$_id",
"name": {"$first":"$name"},
"align": {"$first":"$align"},
"classes":{"$push":"$classes"},
"carrying":{"$first":"$carrying"},
"linked_align":{"$first":"$linked_align"},
"linked_classes":{"$push":{"$arrayElemAt":["$linked_classes",0]}}
}
},
{
"$unwind":"$carrying"
},
{
"$lookup": {
from: "item",
localField: "carrying.itemId",
foreignField: "_id",
as: "linked_carrying"
}
},
{
"$group": {
"_id": "$_id",
"name": {"$first":"$name"},
"align": {"$first":"$align"},
"classes":{"$first":"$classes"},
"linked_align":{"$first":"$linked_align"},
"carrying":{"$push":"$carrying"},
"linked_carrying":{"$push":{"$arrayElemAt":["$linked_carrying",0]}}
}
}
]
Je hebt de $unwind
. niet nodig op de scalaire array (classes
) in versie 3.4 en u kunt de {"classes":{"$push":"$classes"}}
vervangen &{"linked_classes":{"$push":{$arrayElemAt:["$linked_classes",0]}}}
met {"classes":{"$first":"$classes"}}
&{"linked_classes":{"$first":"$linked_classes"}}
respectievelijk.