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. 物化路径模式将每个树节点存储在一个文档中;除了树节点之外,document还将节点祖先或路径的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:考虑以下类别层次结构:
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," }
] )
You can query to retrieve the whole tree, sorting by the field您可以查询以检索整个树,按字段path
:path
排序:db.categories.find().sort( { path: 1 } )
You can use regular expressions on the您可以在path
field to find the descendants ofProgramming
:path
字段中使用正则表达式来查找Programming
的后代:db.categories.find( { path: /,Programming,/ } )
You can also retrieve the descendants of您还可以检索Books
where theBooks
is also at the topmost level of the hierarchy:Books
的子体,其中Books
也位于层次结构的最顶层:db.categories.find( { path: /^,Books,/ } )
To create an index on the field要在path
use the following invocation:path
路径上创建索引,请使用以下调用:db.categories.createIndex( { path: 1 } )
This index may improve performance depending on the query:此索引可能会根据查询情况提高性能:For queries from the root对于根Books
sub-tree (e.g./^,Books,/
or/^,Books,Programming,/
), an index on thepath
field improves the query performance significantly.Books
子树中的查询(例如/^,Books,/
或/^,Books,Programming,/
),path
字段上的索引可显著提高查询性能。For queries of sub-trees where the path from the root is not provided in the query (e.g.对于查询中未提供根路径的子树查询(例如/,Databases,/
), or similar queries of sub-trees, where the node might be in the middle of the indexed string, the query must inspect the entire index./,Databases,/
),或类似的查询,其中节点可能位于索引字符串的中间,查询必须检查整个索引。For these queries an index may provide some performance improvement if the index is significantly smaller than the entire collection.对于这些查询,如果索引明显小于整个集合,则索引可以提供一些性能改进。