Vollfeiw
Vollfeiw

Reputation: 244

Model tree structure in mongo

I'm looking to build a Tree structure for an apps where I'll have to store multiple Tree for each user.

Each tree will be composed of documents for each node :

{
   _id:1,
   user_id:12345,
   category_id:6789,
   data:[]
}

So when I need to, I can access these data with a query looking for user_id and category_id

I was looking on mongoDB Docs and found that : https://docs.mongodb.com/manual/applications/data-models-tree-structures/

Which is pretty interesting, but I have a few questions

Considering that I'll only search for full tree, which solutions is better?
Are child references better, or other structure might do the work better?
And if I use child's references, what is the best way to get all the tree?
Can it be done with a single request or do I have to recursively search for each child ?

I know I could get all docs in one query and kind of build the tree from there, is that a good idea?

EDIT:
So I tried with that:

[{
   _id:1,
   user_id:12345,
   category_id:6789,
   data:{name:"root"},
   parent:null,
   childs:[2,3]
},
{
   _id:2,
   user_id:12345,
   category_id:6789,
   data:{name:"child1"},
   parent:1,
   childs:[]
},
{
   _id:3,
   user_id:12345,
   category_id:6789,
   data:{name:"child2"},
   parent:1,
   childs:[4]
},
{
   _id:4,
   user_id:12345,
   category_id:6789,
   data:{name:"child2_1"},
   parent:3,
   childs:[]
}]

With both parent and children, I can easily find leaves and root when building the tree back. (I chosed to build it in the client app, and query the full tree at once)

The fact is I don't really use parent for now, so it looks "Overkill" to get a reference to the parents, but the query is fast enough, it just take some extra space. Maybe a simple "root" boolean could be better ? I really need some kind of advice with that.

I'm still up to some improvements, I'd like to get this working really fast because each users will have 0 to n tree with 0 to n nodes, and I don't want to mess the data structure for that.

Upvotes: 2

Views: 654

Answers (1)

A K
A K

Reputation: 86

This article shows a similar kind of solution : How to query tree structure recursively with MongoDB?

Other wise parent in consideration, you can query out in this way to convert it to tree

function list_to_tree(list) {
  const map1 = new Map();
  var node,
    roots = [],
    i;

  for (i = 0; i < list.length; i += 1) {
    map1.set(list[i]._id.toString(), i); // initialize the map
    list[i].childs = []; // initialize the children
  }

  for (i = 0; i < list.length; i += 1) {
    node = list[i];
    if (node.parent) {
      list[map1.get(node.parent.toString())].childs.push(node);
    } else {
      roots.push(node);
    }
  }

  let newList = [];
  for (let z = 0; z < roots.length; z++) {
    newList.push(list.filter((x) => x._id === roots[z]._id)[0]);
  }

  return newList;
}

Upvotes: 1

Related Questions