Hi everyone, I’m currently working on an interesting query.
In the database I am using the classic parent-child relationship like this:
{“_id”: ObjectId(…), “parent_id”: str, “name”: “elem1”}, {“_id”: ObjectId(…), “parent_id”: “elem1_id”, “name”: “elem2”}, {“_id”: ObjectId(…), “parent_id”: “elem2_id”, “name”: “elem3”}
The WBS type indicates the root element, the WBEs are intermediate elements and the WPs are leaf elements.
My query is currently structured like this:
db.getCollection("mf-budgeting").aggregate([
{
"$match": {
"type": {"$eq": "WBE"},
"root_id": "671220dd5dc4694e9edee501"
}
},
{
"$addFields": {
"id": {"$toString": "$_id"} // Convertiamo l'_id in stringa se parent_id è stringa
}
},
{
"$graphLookup": {
"from": "mf-budgeting",
"startWith": "$id", // Inizia con l'id (padre)
"connectFromField": "id", // Collega l'_id del nodo padre
"connectToField": "parent_id", // Con il parent_id dei figli
"as": "subtree", // Il risultato verrà messo in "subtree"
"maxDepth": 1000, // Imposta un limite di profondità adeguato
"depthField": "depth" // Aggiungi il campo "depth" per tracciare la profondità
}
},
{
"$match": {
"$expr": {
"$gt": [{"$size": "$subtree"}, 0] // Filtro per includere solo documenti con un sottoalbero
}
}
},
{
"$project": {
"type": 1,
"root_id": 1,
"name": "$anagraphic_section.name",
"subtree": 1,
"depth": 1,
"id": 1,
"parent_id": 1
}
}
])
The problem is that I expected that in the result I would have something like this:
{“_id”: ObjectId(…), “parent_id”: str, “name”: “elem1”, “subtree”: [{“_id”: ObjectId(…), “parent_id”: “elem1_id”, “name”: “elem2”}, {“_id”: ObjectId(…), “parent_id”: “elem2_id”, “name”: “elem3”}]
and so on, where am I going wrong?