On this page本页内容
This page describes a data model that describes a tree-like structure in MongoDB documents by storing full relationship paths between documents.本页描述了一个数据模型,该模型通过存储文档之间的完整关系路径来描述MongoDB文档中的树状结构。
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:考虑以下类别层次结构:
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 of Programming
:path
字段上使用正则表达式来查找Programming
的后代:
db.categories.find( { path: /,Programming,/ } )
You can also retrieve the descendants of 您还可以检索Books
where the Books
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:根据查询,此索引可能会提高性能:
Books
sub-tree (e.g. /^,Books,/
or /^,Books,Programming,/
), an index on the path
field improves the query performance significantly.Books
子树的查询(例如,/^,Books,/
或/^,Books,Programming,/
),路径字段上的索引可以显著提高查询性能。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.对于这些查询,如果索引明显小于整个集合,则索引可以提供一些性能改进。