Database Manual / Data Modeling / Data Model Examples and Patterns / Tree Structures

Model Tree Structures with an Array of Ancestors具有祖先数组的模型树结构

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:考虑以下类别层次结构:

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(祖先)字段外,这些文档还在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.祖先数组模式比物化路径模式稍慢,但使用起来更简单。