在现在的系统多,嵌套组织结构的数据非常常见,在关系型数据库中可以用联合查询来搞定,请各位自行搜索解决。这里主要是提供mongo的设计方法。mongodb的嵌套又引用嵌套还有直接嵌套,这里使用应用嵌套。

加入一个数据结构如下

    @Id
    private String id;
    private String parentId;
    @DBRef
    private List<Item> children = new ArrayList<Item>();

   parentId为父节点的id,这里不能使用dbref,使用会导致引用的死循环。

   children为子节点列表。

   将数据存入到mongo之后,数据如下。

   mongodb嵌套文档结构设计

当我们需要查找某个item的父节点可以直接

db.Item.find({"children.$id": ObjectId("5b835e70060fb022204962db")})
 

比mysql简单粗暴许多倍了吧。

相关文章:

  • 2022-12-23
  • 2021-07-17
  • 2022-02-18
  • 2022-03-03
  • 2021-11-09
  • 2022-12-23
  • 2022-03-01
  • 2022-12-23
猜你喜欢
  • 2021-12-17
  • 2022-02-12
  • 2021-09-17
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案