skip to Main Content

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


  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 …

    Login or Signup to reply.
  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 } }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search