【问题标题】:Model tree structure in mongomongo中的模型树结构
【发布时间】:2021-03-31 10:18:25
【问题描述】:

我正在为一个应用程序构建一个树结构,我必须为每个用户存储多个树。

每棵树将由每个节点的文档组成:

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

因此,当我需要时,我可以通过查找 user_id 和 category_id 的查询来访问这些数据

我正在查看 mongoDB Docs 并发现: https://docs.mongodb.com/manual/applications/data-models-tree-structures/

这很有趣,但我有几个问题

考虑到我只会搜索完整的树,哪种解决方案更好?
子引用是否更好,或者其他结构可能做得更好?
如果我使用孩子的参考资料,获得所有树的最佳方法是什么?
可以通过单个请求完成还是我必须递归搜索每个孩子?

我知道我可以在一个查询中获取所有文档并从那里构建树,这是个好主意吗?

编辑:
所以我尝试了:

[{
   _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:[]
}]

有了父母和孩子,我可以在重建树时轻松找到叶子和根。 (我选择在客户端构建,一次查询全树)

事实上,我现在并没有真正使用 parent,因此获取对 parent 的引用看起来“矫枉过正”,但查询速度足够快,只是需要一些额外的空间。也许一个简单的“根”布尔值会更好?我真的需要一些建议。

我还在做一些改进,我想让它工作得非常快,因为每个用户都会有 0 到 n 个树和 0 到 n 个节点,我不想为此弄乱数据结构.

【问题讨论】:

    标签: mongodb tree


    【解决方案1】:

    这篇文章展示了一种类似的解决方案:How to query tree structure recursively with MongoDB?

    考虑其他明智的父母,您可以通过这种方式查询将其转换为树

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多