本文共 400 字,大约阅读时间需要 1 分钟。
在现在的系统多,嵌套组织结构的数据非常常见,在关系型数据库中可以用联合查询来搞定,请各位自行搜索解决。这里主要是提供mongo的设计方法。mongodb的嵌套又引用嵌套还有直接嵌套,这里使用应用嵌套。
加入一个数据结构如下
private String id; private String parentId; @DBRef private List<Item> children = new ArrayList<Item>();
parentId为父节点的id,这里不能使用dbref,使用会导致引用的死循环。
children为子节点列表。
将数据存入到mongo之后,数据如下。
当我们需要查找某个item的父节点可以直接
db.Item.find({"children.$id": ObjectId("5b835e70060fb022204962db")})
比mysql简单粗暴许多倍了吧。
转载地址:http://mctil.baihongyu.com/