On this page本页内容
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文档中的树状结构。
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:考虑以下类别层次结构:
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:
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.祖先数组模式略慢于物化路径模式,但更易于使用。