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:
Copy { "_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: