Model Tree Structures with Parent References
Overview
This page describes a data model that describes a tree-likestructure in MongoDB documents by storingreferences to “parent” nodes inchildren nodes.
Pattern
The Parent References pattern stores each tree node in a document; inaddition to the tree node, the document stores the id of the node’sparent.
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
:
- db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
- db.categories.insert( { _id: "dbm", parent: "Databases" } )
- db.categories.insert( { _id: "Databases", parent: "Programming" } )
- db.categories.insert( { _id: "Languages", parent: "Programming" } )
- db.categories.insert( { _id: "Programming", parent: "Books" } )
- db.categories.insert( { _id: "Books", parent: null } )
- The query to retrieve the parent of a node is fast andstraightforward:
- db.categories.findOne( { _id: "MongoDB" } ).parent
- You can create an index on the field
parent
to enable fast searchby the parent node:
- db.categories.createIndex( { parent: 1 } )
- You can query by the
parent
field to find its immediate childrennodes:
- db.categories.find( { parent: "Databases" } )
- To retrieve subtrees, see
$graphLookup
.