Model Tree Structures with an Array of Ancestors使用祖先数组对树结构进行建模

On this page本页内容

Overview概述

This page describes a data model that describes a tree-like structure in MongoDB documents using references to parent nodes and an array that stores all ancestors.本页描述了一个数据模型,该模型使用对父节点的引用和存储所有祖先的数组来描述MongoDB文档中的树状结构。

Pattern模式

The Array of Ancestors 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 ancestors or path.祖先数组模式将每个树节点存储在文档中;除了树节点外,文档还将节点的祖先或路径的id存储在一个数组中。

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

Tree data model for a sample hierarchy of categories.

The following example models the tree using Array of Ancestors. 下面的示例使用祖先数组对树进行建模。In addition to the ancestors field, these documents also store the reference to the immediate parent category in the parent field:除了ancestors字段外,这些文档还在父字段中存储对直接父类别的引用:

db.categories.insertMany( [
  { _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
  { _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
  { _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" },
  { _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" },
  { _id: "Programming", ancestors: [ "Books" ], parent: "Books" },
  { _id: "Books", ancestors: [ ], parent: null }
] )

The Array of Ancestors pattern provides a fast and efficient solution to find the descendants and the ancestors of a node by creating an index on the elements of the ancestors field. 祖先数组模式提供了一种快速高效的解决方案,通过在祖先字段的元素上创建索引来查找节点的后代和祖先。This makes Array of Ancestors a good choice for working with subtrees.这使得祖先数组成为处理子树的好选择。

The Array of Ancestors pattern is slightly slower than the Materialized Paths pattern but is more straightforward to use.祖先数组模式略慢于物化路径模式,但更易于使用。