Model Tree Structures with Materialized Paths具有物化路径的树结构模型

On this page本页内容

Overview概述

This page describes a data model that describes a tree-like structure in MongoDB documents by storing full relationship paths between documents.本页描述了一个数据模型,该模型通过存储文档之间的完整关系路径来描述MongoDB文档中的树状结构。

Pattern模式

The Materialized Paths pattern stores each tree node in a document; in addition to the tree node, document stores as a string the id(s) of the node’s ancestors or path. 物化路径模式将每个树节点存储在文档中;除了树节点外,文档还以字符串形式存储节点祖先或路径的id。Although the Materialized Paths pattern requires additional steps of working with strings and regular expressions, the pattern also provides more flexibility in working with the path, such as finding nodes by partial paths.虽然物化路径模式需要处理字符串和正则表达式的额外步骤,但该模式在处理路径时也提供了更大的灵活性,例如通过部分路径查找节点。

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

Tree data model for a sample hierarchy of categories.

The following example models the tree using Materialized Paths, storing the path in the field path; the path string uses the comma , as a delimiter:下面的示例使用物化路径对树进行建模,将路径存储在字段path中;路径字符串使用逗号,作为分隔符:

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