Puoi usare $graphLookup insieme ad altri operatori utili sugli array:
$match: filtra i soli record conparent_iduguale anull.$graphLookup: recupera i record figli e il livello di profondità nel campoleveldefinito dadepthField.$unwind: destruttura l'arraychildrenmantenendo anche gli array vuoti.$sort: ordina per il campo di profonditàlevelin ordine decrescente.$group: raggruppa per il campoide ricostruisce l'arraychildren.
db.collection.aggregate([
{ $match: { parent_id: null } },
{ $graphLookup: {
from: "collection",
startWith: "$id",
connectFromField: "id",
connectToField: "parent_id",
depthField: "level",
as: "children"
} },
{ $unwind: { path: "$children", preserveNullAndEmptyArrays: true } },
{ $sort: { "children.level": -1 } },
{ $group: {
_id: "$id",
parent_id: { $first: "$parent_id" },
name: { $first: "$name" },
type: { $first: "$type" },
category: { $first: 1 },
children: { $push: "$children" }
} }
- A questo punto
$addFieldsindividua i figli del livello annidato e li assegna al rispettivo livello:$reduceitera sull'arraychildren.- Inizializza i campi di default:
levela -1,presentChildeprevChilda array vuoti, per le condizioni. $letinizializza i campi:prevrestituisceprevChildse i duelevelsono uguali, altrimentipresentChild;currentrestituiscepresentChildse i livelli sono uguali, altrimenti un array vuoto.
inrestituisce i campileveleprevChilddai campi inizializzati:presentChildfiltrachildrendall'arraypreve unisce gli oggetti correnti con l'arraychildrentramite$mergeObjects, concatenandoli concurrenttramite$concatArrays.
- Un ulteriore
$addFieldsrestituisce solo l'arraypresentChild, l'unico che ci interessa.
{ $addFields: {
children: { $reduce: {
input: "$children",
initialValue: { level: -1, presentChild: [], prevChild: [] },
in: { $let: {
vars: {
prev: { $cond: [
{ $eq: ["$$value.level", "$$this.level"] },
"$$value.prevChild", "$$value.presentChild"
] },
current: { $cond: [
{ $eq: ["$$value.level", "$$this.level"] },
"$$value.presentChild", []
] }
},
in: {
level: "$$this.level",
prevChild: "$$prev",
presentChild: { $concatArrays: [
"$$current",
[ { $mergeObjects: [ "$$this", {
children: { $filter: {
input: "$$prev", as: "e",
cond: { $eq: ["$$e.parent_id", "$$this.id"] }
} }
} ] } ]
] }
}
} }
} }
} },
{ $addFields: { id: "$_id", children: "$children.presentChild" } }
])
Esempio su Playground.
Semplificazione
Se devi solo costruire l'albero e non ordinare i figli per profondità, puoi omettere $unwind, $sort, $group e il $reduce finale: $graphLookup restituisce già i discendenti con il campo level, che puoi riorganizzare con un unico passaggio.