Model Tree Structures with Child References具有子引用的模型树结构

On this page本页内容

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.子引用模式将每个树节点存储在文档中;除树节点外,文档还以数组形式存储节点子节点的id。

Consider the following hierarchy of categories:考虑以下类别的层次结构:

Tree data model for a sample 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 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.该模式还可以为存储一个节点可能有多个父节点的图提供合适的解决方案。