search

Home  >  Q&A  >  body text

树形结构 - MongoDB 如何存储有序树表?

需要在MongoDB里存储一个有序的树表

例如

- 1,a
- 
    - 11,b

- 2,c
- 
    - 21,d
    - 22,e
    - 
        - 221,f

    - 23,g

- 3,h

根据MongoDB官方文档
http://docs.mongodb.org/manual/tutorial/model-tree-structures/
里的各种方案,同级的文档是没有顺序的。但是我需要能排序(能体现该文档在本级中的上下位置) 同时需要在同级中移动和插入新数据。

目前我能想到的方案

方案1,将该文档在本级的顺序写到文档内。

问题:

  1. 每修改一个文档位置,就需要批量修改本级所有记录,在mongoDB里这种批量修改成本是否很高?
  2. 如果多个并发修改,是否会造成数据不一致?

方案2,在上级文档中保存一个下级文档排列顺序的数组

问题:

  1. 这个查询要怎么写?
  2. 这种每次查询都要排序的查询是否系统成本很高(占用大量cpu和内存)?
黄舟黄舟2797 days ago1042

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-24 09:14:53

    Concerning tree structures, there are multiple modeling methods. Which one did you use?

    If your order is natural order, you can get sequential results by indexing the path field. Especially the method of materializing paths. Such as:

    { path: "1a", ...}
    { path: "1a,b",  ...}
    { path: "2c", ...}
    { path: "2c,d", ...}
    { path: "2c,e", ...}
    { path: "2c,e,f", ...}
    

    This method can quickly query all byte points under a node, and all nodes can be sorted according to path

    See the Chinese document being translated: http://docs.mongoing.com/manual-zh/tutorial/model-tree-structures-with-materialized-paths.html

    reply
    0
  • Cancelreply