Model Tree Structures with Child References
Overview
This page describes a data model that describes a tree-like structurein MongoDB documents by storing references in the parent-nodes to children nodes.
Pattern
The Child References pattern stores each tree node in a document; inaddition to the tree node, document stores in an array the id(s) of thenode’s children.
Consider the following hierarchy of categories:
The following example models the tree using Child References, storingthe reference to the node’s children in the field children
:
- db.categories.insert( { _id: "MongoDB", children: [] } )
- db.categories.insert( { _id: "dbm", children: [] } )
- db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )
- db.categories.insert( { _id: "Languages", children: [] } )
- db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )
- db.categories.insert( { _id: "Books", children: [ "Programming" ] } )
- The query to retrieve the immediate children of a node is fast andstraightforward:
- db.categories.findOne( { _id: "Databases" } ).children
- You can create an index on the field
children
to enable fastsearch by the child nodes:
- db.categories.createIndex( { children: 1 } )
- You can query for a node in the
children
field to find its parentnode as well as its siblings:
- db.categories.find( { children: "MongoDB" } )
The Child References pattern provides a suitable solution to tree storageas long as no operations on subtrees are necessary. This pattern mayalso provide a suitable solution for storing graphs where a node mayhave multiple parents.