'Which database that can handle deeply nested object? [closed]
Let say 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 really possible? Which kind 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 of the data by specific ID and its children.
If I want to get id 3, I just need to get it and it's children.
For now I'm using mongodb but I think it complicated. I can only get result by find the root data, then do javascript looping to get its child.
Solution 1:[1]
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 ...
Solution 2:[2]
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.
var seekId = 6;
db.foo.aggregate([
{$project: {X: {$function: {
body: function(doc, target) {
var found = undefined;
var inner = function(item, depth) {
if(item['id'] == target) {
found = item;
found['_depth'] = depth;
delete found['children']; // or don't to show the whole tree
} else {
if(item['children'] != undefined) {
for(var i = 0; i < item['children'].length; i++) {
var cc = item['children'][i];
inner(cc, depth+1);
if(found != null) {
break;
}
}
}
}
}
inner(doc,0);
return found;
},
args: [ '$$ROOT', seekId ],
lang: "js"
}}
}}
// Don't show docs that had no matches (or show them if you like):
,{$match: {X: {$ne:null}}}
]);
{ "_id" : 1, "X" : { "label" : "sixth", "id" : 6, "_depth" : 2 } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R2D2 |
| Solution 2 | Buzz Moschetti |
