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 query to retrieve the immediate children of a node is fast and straightforward:检索节点的直接子节点的查询既快速又直观:

    db.categories.findOne( { _id: "Databases" } ).children
  • You can create an index on the field children to enable fast search by the child nodes:您可以在字段children上创建索引,以启用子节点的快速搜索:

    db.categories.createIndex( { children: 1 } )
  • You can query for a node in the children field 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.该模式还可以提供用于存储图的合适解决方案,其中节点可以具有多个父节点。

←  Model Tree Structures with Parent ReferencesModel Tree Structures with an Array of Ancestors →