I want to get object like this:
[
{
label: "first",
id: 1,
children: []
},
{
label: "second",
id: 2,
children: [
{
label: "third",
id: 3,
children: [
{
label: "fifth",
id: 5,
children: []
},
{
label: "sixth",
id: 6,
children: [
{
label: "seventh",
id: 7,
children: []
}
]
}
]
},
{
label: "fourth",
id: 4,
children: []
}
]
}
];
Is this kind of database design possible? Which database should I learn to get this result or should I change the database design?
I want to do 1 HTTP request then get all data by specific ID and its children so if I want to get id 3, I just need to get it and its children. I’m using MongoDB but I think it’s complicated. I can only get results by finding the root data, then do JavaScript looping to get its child.
2
Answers
In mongoDB you can have up to 100 nested levels in single document ,
If you need to get id:3 , you can use the aggregation framework to $filter all objects in children with id:3 , you dont need to loop via javascript every time …
Here is a nice use of recursion in MongoDB to find a target
id
nested somewhere in each doc and throws in the depth at which it is found.