I have the following schema in my taxon
collection :
{
\"_id\": 1,
\"na\": [ \"root_1\",
\"root_2\",
\"root_3\" ],
\"pa\":
You can try below aggregation.
Stages $match - $graphLookup - $project
.
$reduce
to pick the first element from the each of $graphLookup
nameList's
na
array.
db.taxon.aggregate([{
$match: {
_id: {
$in: listId
}
}
}, {
$graphLookup: {
from: "taxon",
startWith: "$_id",
connectFromField: "pa",
connectToField: "_id",
as: "nameList"
}
}, {
$project: {
nameList: {
$reduce: {
input: "$nameList",
initialValue: [],
in: {
"$concatArrays": ["$$value", {
$slice: ["$$this.na", 1]
}]
}
}
}
}
}])