Model Tree Structures with Parent References具有父引用的模型树结构

On this page本页内容

Overview概述

This page describes a data model that describes a tree-like structure in MongoDB documents by storing references to "parent" nodes in children nodes.本页描述了一个数据模型,该模型通过在子节点中存储对“父”节点的引用来描述MongoDB文档中的树状结构。

Pattern模式

The Parent References pattern stores each tree node in a document; in addition to the tree node, the document stores the id of the node's parent.父引用模式将每个树节点存储在文档中;除了树节点外,文档还存储节点父节点的id。

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

Tree data model for a sample hierarchy of categories.

The following example models the tree using Parent References, storing the reference to the parent category in the field parent:下面的示例使用父引用对树进行建模,将对父类别的引用存储在字段parent中:

db.categories.insertMany( [
   { _id: "MongoDB", parent: "Databases" },
   { _id: "dbm", parent: "Databases" },
   { _id: "Databases", parent: "Programming" },
   { _id: "Languages", parent: "Programming" },
   { _id: "Programming", parent: "Books" },
   { _id: "Books", parent: null }
] )
  • The query to retrieve the parent of a node is fast and straightforward:检索节点父节点的查询既快速又直观:

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

    db.categories.createIndex( { parent: 1 } )
  • You can query by the parent field to find its immediate children nodes:您可以按parent字段查询以查找其直接子节点:

    db.categories.find( { parent: "Databases" } )
  • To retrieve subtrees, see $graphLookup.要检索子树,请参阅$graphLookup
←  Model Tree StructuresModel Tree Structures with Child References →