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:

Tree data model for a sample hierarchy of categories.

The following example models the tree using Parent References,storing the reference to the parent category in the field parent:

  1. db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
  2. db.categories.insert( { _id: "dbm", parent: "Databases" } )
  3. db.categories.insert( { _id: "Databases", parent: "Programming" } )
  4. db.categories.insert( { _id: "Languages", parent: "Programming" } )
  5. db.categories.insert( { _id: "Programming", parent: "Books" } )
  6. db.categories.insert( { _id: "Books", parent: null } )
  • The query to retrieve the parent of a node is fast andstraightforward:
  1. db.categories.findOne( { _id: "MongoDB" } ).parent
  • You can create an index on the field parent to enable fast searchby the parent node:
  1. db.categories.createIndex( { parent: 1 } )
  • You can query by the parent field to find its immediate childrennodes:
  1. db.categories.find( { parent: "Databases" } )