Storing Tree like Hierarchy Structures With MongoDB, Part 2

Introduction

In real life almost any project deals with the tree structures. Different kinds of taxonomies, site structures etc require modelling of hierarchy relations. In this article I will illustrate using last two of five typical approaches of operating with hierarchy data on example of the MongoDB database. Please refer to fist article from the series to read about first three ones. Those approaches are:

  • Model Tree Structures with Child References
  • Model Tree Structures with Parent References
  • Model Tree Structures with an Array of Ancestors
  • Model Tree Structures with Materialized Paths
  • Model Tree Structures with Nested Sets

Note: article is inspired by another article ‘Model Tree Structures in MongoDB’ by 10gen, but does not copy it, but provides additional examples on typical operations with tree management. Please refer for 10gen’s article to get more solid understanding of the approach.

Background

As a demo dataset I use some fake eshop goods taxonomy.

Challenges to address

In a typical site scenario, we should be able to

  • Operate with tree (insert new node under specific parent, update/remove existing node, move node across the tree)
  • Get path to node (for example, in order to be build the breadcrumb section)
  • Get all node descendants (in order to be able, for example, to select goods from more general category, like ‘Cell Phones and Accessories’ which should include goods from all subcategories.

On each of the examples below we:

  • Add new node called ‘LG’ under electronics
  • Move ‘LG’ node under Cell_Phones_And_Smartphones node
  • Remove ‘LG’ node from the tree
  • Get child nodes of Electronics node
  • Get path to ‘Nokia’ node
  • Get all descendants of the ‘Cell_Phones_and_Accessories’ node

Please refer to image above for visual representation.

Tree structure using Materialized Path

For each node we store (ID, PathToNode)

Approach looks similar to storing array of ancestors, but we store a path in form of string instead. In example above I intentionally use comma(,) as a path elements divider in order to keep regular expression simpler.

Adding new node

New node insertion is done with one select and one insert operation

Hide Copy Code

Updating/moving the node

Node can be moved using one select and one update operation

Hide Copy Code

Node removal

Node can be removed using single database query

Hide Copy Code

Getting node children, unordered

Note unless you introduce the order field, it is impossible to get ordered list of node children. You should consider another approach if you need order.

Hide Copy Code

Getting all node descendants

Single select, regexp starts with ^ which allows using the index for matching

Hide Copy Code

Getting path to node

We can obtain path directly from node without issuing additional selects.

Hide Copy Code

Indexes

Recommended index is putting index on path

Hide Copy Code

Tree structure using Nested Sets

For each node we store (ID, left, right).

Left field also can be treated as an order field

Adding new node

Please refer to image above. Assume, we want to insert LG node after shop_top_products(14,23).
New node would have left value of 24, affecting all remaining left values according to traversal rules, and will have right value of 25, affecting all remaining right values including root one.

Steps:

  1. take next node in traversal tree
  2. new node will have left value of the following sibling and right value — incremented by two following sibling’s left one
  3. now we have to create the place for the new node. Update affects right values of all ancestor nodes and also affects all nodes that remain for traversal
  4. Only after creating place new node can be inserted

Hide Copy Code

Let’s check the result:

Hide Copy Code

Node removal

While potentially rearranging node order within same parent is identical to exchanging node’s left and right values,the formal way of moving the node is first removing node from the tree and later inserting it to new location. Node: node removal without removing it’s childs is out of scope for this article. For now, we assume, that node to remove has no children, i.e. right-left=1

Steps are identical to adding the node — i.e. we adjusting the space by decreasing affected left/right values,
and removing original node.

Hide Copy Code

Let’s check result:

Hide Copy Code

Updating/moving the single node

Moving the node can be within same parent, or to another parent. If the same parent, and nodes are without childs, than you need just to exchange nodes (left,right) pairs.

Formal way is to remove node and insert to new destination, thus the same restriction apply — only node without children can be moved. If you need to move subtree, consider creating mirror of the existing parent under new location, and move nodes under the new parent one by one. Once all nodes moved, remove obsolete old parent.

As an example, lets move LG node from the insertion example under the Cell_Phones_and_Smartphones node, as a last sibling (i.e. you do not have following sibling node as in the insertion example)

Steps

  1. to remove LG node from tree using node removal procedure described above
  2. to take right value of the new parent.New node will have left value of the parent’s right value and right value — incremented by one parent’s right one. Now we have to create the place for the new node: update affects right values of all nodes on a further traversal path

Hide Copy Code

Let’s check result:

Hide Copy Code

Getting all node descendants

This is core stength of this approach — all descendants retrieved using one select to DB. Moreover,by sorting by node left — the dataset is ready for traversal in a correct order

Hide Copy Code

Getting path to node

Retrieving path to node is also elegant and can be done using single query to database:

Hide Copy Code

Indexes

Recommended index is putting index on left and right values:

Hide Copy Code

And, in case if you were so patient to read the article till this section, bonus:

Tree structure using combination of Nested Sets and classic Parent reference with order approach

For each node we store (ID, Parent, Order,left, right).

Left field also is treated as an order field, so we could omit order field. But from other hand
we can leave it, so we can use Parent Reference with order data to reconstruct left/right values in case of accidental corruption, or, for example during initial import.

Adding new node

Adding new node can be adopted from Nested Sets in this manner:

Hide Copy Code

Before insertion

Hide Copy Code

After insertion:

Hide Copy Code

Updating/moving the single node

Identical to insertion approach

Node removal

Approach from Nested Sets is used.

Getting node children, ordered

Now is possible by using (Parent,Order) pair

Hide Copy Code

Getting all node descendants

Approach from Nested Sets is used.

Getting path to node

Approach from nested sets is used

Code in action

Code can be downloaded from repository https://github.com/Voronenko/Storing_TreeView_Structures_WithMongoDB

All files are packaged according to the following naming convention:

  • MODELReference.js — initialization file with tree data for MODEL approach
  • MODELReference_operating.js — add/update/move/remove/get children examples
  • MODELReference_pathtonode.js — code illustrating how to obtain path to node
  • MODELReference_nodedescendants.js — code illustrating how to retrieve all the descendands of the node

All files are ready to use in mongo shell. You can run examples by invoking mongo < file_to_execute, or, if you want, interactively in the shell or with RockMongo web shell.

Software engineer, with project management background. Founder @ softasap.com — cool automation for the people :) — have a problem that needs to be solved?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store