Overview概述
This page describes a data model that describes a tree-like structure in MongoDB documents by storing references in the parent-nodes to children nodes.此页面描述了一个数据模型,该模型通过在父节点中存储对子节点的引用来描述MongoDB文档中的树状结构。
Pattern模式
The Child References pattern stores each tree node in a document; in addition to the tree node, document stores in an array the id(s) of the node's children.子引用模式将每个树节点存储在文档中;除了树节点之外,document还在数组中存储节点子节点的id。
Consider the following hierarchy of categories:考虑以下类别层次结构:
The following example models the tree using Child References, storing the reference to the node's children in the field 以下示例使用子引用对树进行建模,将对节点子节点的引用存储在字段children:children中:
db.categories.insertMany( [
{ _id: "MongoDB", children: [] },
{ _id: "dbm", children: [] },
{ _id: "Databases", children: [ "MongoDB", "dbm" ] },
{ _id: "Languages", children: [] },
{ _id: "Programming", children: [ "Databases", "Languages" ] },
{ _id: "Books", children: [ "Programming" ] }
] )
The query to retrieve the immediate children of a node is fast and straightforward:检索节点的直接子节点的查询既快速又简单:db.categories.findOne( { _id: "Databases" } ).childrenYou can create an index on the field您可以在字段childrento enable fast search by the child nodes:children上创建索引,以实现子节点的快速搜索:db.categories.createIndex( { children: 1 } )You can query for a node in the您可以在childrenfield to find its parent node as well as its siblings:children字段中查询节点,以找到其父节点及其兄弟节点:db.categories.find( { children: "MongoDB" } )
The Child References pattern provides a suitable solution to tree storage as long as no operations on subtrees are necessary. This pattern may also provide a suitable solution for storing graphs where a node may have multiple parents.只要不需要对子树进行操作,子引用模式就为树存储提供了一种合适的解决方案。这种模式还可以为存储节点可能有多个父节点的图提供合适的解决方案。