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.祖先数组模式将每个树节点存储在一个文档中;除了树节点之外,document还在数组中存储节点祖先或路径的id。
Consider the following 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
字段外,这些文档还在parent
字段中存储对直接父类别的引用:
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 query to retrieve the ancestors or path of a node is fast and straightforward:检索节点的祖先或路径的查询既快捷又直观:db.categories.findOne( { _id: "MongoDB" } ).ancestors
You can create an index on the field您可以在字段ancestors
to enable fast search by the ancestors nodes:ancestors
上创建索引,以便按祖先节点进行快速搜索:db.categories.createIndex( { ancestors: 1 } )
You can query by the field您可以按字段ancestors
to find all its descendants:ancestors
查询以查找其所有后代:db.categories.find( { ancestors: "Programming" } )
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.祖先数组模式比实体化路径模式稍慢,但使用起来更简单。