This version of the documentation is archived and no longer supported.

Model Tree Structures with Parent References

On this page


Data in MongoDB has a flexible schema. Collections do not enforce document structure. Decisions that affect how you model data can affect application performance and database capacity. See Data Modeling Concepts for a full high level overview of data modeling in MongoDB.

This document describes a data model that describes a tree-like structure in MongoDB documents by storing references to “parent” nodes in children nodes.


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:

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:

db.categories.insertMany( [
   { _id: "MongoDB", parent: "Databases" },
   { _id: "dbm", parent: "Databases" },
   { _id: "Databases", parent: "Programming" },
   { _id: "Languages", parent: "Programming" },
   { _id: "Programming", parent: "Books" },
   { _id: "Books", parent: null }
] )
  • The query to retrieve the parent of a node is fast and straightforward:

    db.categories.findOne( { _id: "MongoDB" } ).parent
  • You can create an index on the field parent to enable fast search by the parent node:

    db.categories.createIndex( { parent: 1 } )
  • You can query by the parent field to find its immediate children nodes:

    db.categories.find( { parent: "Databases" } )
  • To retrieve subtrees, see $graphLookup.