- Data Models >
- Data Model Examples and Patterns >
- Model Tree Structures >
- Model Tree Structures with Parent References
Model Tree Structures with Parent References¶
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.
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.
Consider the following hierarchy of categories:
The following example models the tree using Parent References,
storing the reference to the parent category in the field parent
:
The query to retrieve the parent of a node is fast and straightforward:
You can create an index on the field
parent
to enable fast search by the parent node:You can query by the
parent
field to find its immediate children nodes:To retrieve subtrees, see
$graphLookup
.