-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-pipeline-mongodb
32 lines (32 loc) · 1.44 KB
/
tree-pipeline-mongodb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[
{
'$match': {
'parent': null
}
}, {
'$graphLookup': {
'from': 'tree',
'startWith': '$_id',
'connectFromField': '_id',
'connectToField': 'parent',
'as': 'children',
'depthField': 'level'
}
}, {
'$match': {
'parent': null
}
}, {
'$addFields': {
'children': {
'$function': {
'body': 'function(children,root) {\n const obj=Object.assign({},root)\n const map={}\n children.sort((a,b)=>{\n if(a.level<b.level){\n return -1\n }\n else{\n return 1\n }\n }).reduce((acc,curr)=>{\n if(!acc[curr.id]){\n acc[curr._id]=curr\n acc[curr._id].children=[]\n }\n if(acc[curr.parent])\n acc[curr.parent].children.push(curr)\n return acc;\n },map)\n\n const arr=Object.values(map).filter((val)=>val.level==0)\n\n return arr \n }',
'args': [
'$children', '$$ROOT'
],
'lang': 'js'
}
}
}
}
]