Issue
Hello Below I have specify the data which is to be used and get an output which I have mentioned below, Can you please help me on that as I tried alot but couldn't find a way.
//This is the data
let data = [
{'name': 'A', 'parent': null},
{'name': 'B', 'parent': null},
{'name': 'C', 'parent': 'A'},
{'name': 'D', 'parent': 'A'},
{'name': 'E', 'parent': 'D'},
{'name': 'F', 'parent': 'D'},
{'name': 'G', 'parent': 'B'},
{'name': 'H', 'parent': 'B'},
];
//And want the output like this by using mongodb aggregation
{
"null": [
{
"A": [
{
"C": []
},
{
"D": [
{
"E": []
},
{
"F": []
}
]
}
]
},
{
"B": [
{
"G": []
},
{
"H": []
}
]
}
]
}
I have tried using graphlookup aggregation but couldn't find a way out of it.
Thanks for your help !
Solution
Try this:
db.collection.aggregate([
{
$lookup: {
from: "collection",
let: { name: "$name" },
pipeline: [
{
$match: {
$expr: { $eq: ["$parent", "$$name"] }
}
},
{
$lookup: {
from: "collection",
let: { name: "$name" },
pipeline: [
{
$match: {
$expr: { $eq: ["$parent", "$$name"] }
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: [[{ k: "$name", v: [] }]]
}
}
}
],
as: "children"
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: [[{ k: "$name", v: "$children" }]]
}
}
}
],
as: "children"
}
},
{
$match: {
children: { $ne: [] },
parent: null
}
},
{
$group: {
_id: "$parent",
array: {
$push: {
array: [{ k: "$name", v: "$children" }]
}
}
}
},
{
$addFields: {
array: {
$map: {
input: "$array",
as: "item",
in: { $arrayToObject: "$$item.array" }
}
}
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: [[{ k: "null", v: "$array" }]] }
}
}
]);
Output:
{
"null" : [
{
"A" : [
{
"C" : [ ]
},
{
"D" : [
{
"E" : [ ]
},
{
"F" : [ ]
}
]
}
]
},
{
"B" : [
{
"G" : [ ]
},
{
"H" : [ ]
}
]
}
]
}
Answered By - Dheemanth Bhat Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.