Anda harus $unwind
untuk meratakan skalar dan sub dokumen asing _id dan tambahkan $group
tahap di ujung pipa untuk mendapatkan kembali struktur aslinya.
$first
akumulator untuk menyimpan kolom dan $push
dengan $arrayElemAt
untuk mengumpulkan nilai larik untuk menyesuaikan $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]}}
}
}
]
Anda tidak memerlukan $unwind
pada array skalar (classes
) dalam versi 3.4 dan Anda dapat mengganti {"classes":{"$push":"$classes"}}
&{"linked_classes":{"$push":{$arrayElemAt:["$linked_classes",0]}}}
dengan {"classes":{"$first":"$classes"}}
&{"linked_classes":{"$first":"$linked_classes"}}
masing-masing.