Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Using MongoDB Aggregation to Build Hierarchical Category Structures

1 min read .
Using MongoDB Aggregation to Build Hierarchical Category Structures

Applications often need to represent hierarchical data such as parent categories, child categories, and deeper descendants. MongoDB’s aggregation framework includes $graphLookup, which can recursively traverse relationships within a collection.

This article shows how to use $graphLookup to retrieve a category hierarchy from documents that reference their parent category.

1. Data Structure

Consider the following documents in a MongoDB collection:

{ "_id" : 1, "cat_id" : 1, "title" : "Parent Category", "parent" : null }
{ "_id" : 2, "cat_id" : 2, "title" : "Child Category", "parent" : 1 }
{ "_id" : 3, "cat_id" : 3, "title" : "Sub Child Category", "parent" : 2 }

The relationships are:

  • Parent Category → the root category.
  • Child Category → a child of Parent Category.
  • Sub Child Category → a child of Child Category.

2. Use $graphLookup to Traverse the Hierarchy

The $graphLookup stage performs recursive lookups, which makes it useful for following parent-child relationships.

Example aggregation pipeline:

db.categories.aggregate([
  {
    $match: { "parent": null }
  },
  {
    $graphLookup: {
      from: "categories",
      startWith: "$_id",
      connectFromField: "_id",
      connectToField: "parent",
      as: "subCategory"
    }
  }
])

How it works:

  • $match: { "parent": null } → selects root categories that have no parent.

  • $graphLookup → recursively finds descendants.

    • from → the collection to search, here categories.
    • startWith → the initial value used to begin traversal, here the root document’s _id.
    • connectFromField → the field whose value is used to continue traversal, _id.
    • connectToField → the field matched against that value, parent.
    • as → the field that receives all matching descendants, subCategory.

3. Aggregation Result

The pipeline returns each root category along with all descendants found by the graph traversal:

{
  _id: 1,
  cat_id: 1,
  title: 'Parent Category',
  parent: null,
  subCategory: [
    { _id: 2, cat_id: 2, title: 'Child Category', parent: 1 },
    { _id: 3, cat_id: 3, title: 'Sub Child Category', parent: 2 }
  ]
}

The subCategory array contains descendants discovered across all traversed levels. Note that $graphLookup returns a flat array of matching documents; if your application needs a deeply nested tree structure, you will need an additional transformation step in the database pipeline or application code.

4. Conclusion

MongoDB’s $graphLookup is a practical tool for traversing hierarchical or graph-like relationships stored in a collection. It is useful for categories, organizational structures, dependency graphs, and other data models in which documents reference parent or related documents.

chevron-up