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:

Tree data model for a sample hierarchy of categories.

The following example models the tree using Child References, storingthe reference to the node’s children in the field children:

  1. db.categories.insert( { _id: "MongoDB", children: [] } )
  2. db.categories.insert( { _id: "dbm", children: [] } )
  3. db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )
  4. db.categories.insert( { _id: "Languages", children: [] } )
  5. db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )
  6. db.categories.insert( { _id: "Books", children: [ "Programming" ] } )
  • The query to retrieve the immediate children of a node is fast andstraightforward:
  1. db.categories.findOne( { _id: "Databases" } ).children
  • You can create an index on the field children to enable fastsearch by the child nodes:
  1. db.categories.createIndex( { children: 1 } )
  • You can query for a node in the children field to find its parentnode as well as its siblings:
  1. 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.