Storing Tree like Hierarchy Structures With MongoDB

Introduction

In a real life almost any project deals with the tree structures. Different kinds of taxonomies, site structures etc require modeling of hierarchy relations. In this article I will illustrate using first three of five typical approaches of operating with hierarchy data on example of the MongoDB database. 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 with parent reference

This is most commonly used approach. For each node we store (ID, ParentReference, Order)

Operating with tree

Pretty simple, but changing the position of the node within siblings will require additional calculations. You might want to set high numbers like item position * 10⁶ for order in order to be able to set new node order as trunc (lower sibling order — higher sibling order)/2 — this will give you enough operations, until you will need to traverse whole the tree and set the order defaults to big numbers again

Adding new node

Good points: requires only one insert operation to introduce the node.

Updating/moving the node

Good points: as during insert — requires only one update operation to amend the node

Node removal

Good points: requires single operation to remove the node from tree

Getting node children, ordered

Good points: all childs can be retrieved from database and ordered using single call.

Getting all node descendants

Bad points: unfortunately, requires recursive calls to database.

Getting path to node

Bad points: unfortunately also require recursive operations to get the path.

Indexes

Recommended index is on fields parent and order

Tree structure with childs reference

For each node we store (ID, ChildReferences).

Please note, that in this case we do not need order field, because Childs collection already provides this information. Most of languages respect the array order. If this is not in case for your language, you might consider additional coding to preserve order, however this will make things more complicated

Adding new node

Note: requires one insert operation and one update operation to insert the node.

Updating/moving the node

Requires single update operation to change node order within same parent, requires two update operations, if node is moved under another parent.

rearranging order under the same parent

moving the node

Node removal

Node removal also requires two operations: one update and one remove.

Getting node children, ordered

Bad points: requires additional client side sorting by parent array sequence. Depending on result set, it may affect speed of your code.

Result set:

As you see, we have ordered array childs, which can be used to sort the result set on a client

Getting all node descendants

Note: also recursive operations, but we need less selects to databases comparing to previous approach

Getting path to node

Path is calculated recursively, so we need to issue number of sequential calls to database.

Indexes

Recommended index is putting index on childs:

Tree structure using an Array of Ancestors

For each node we store (ID, ParentReference, AncestorReferences)

Adding new node

You need one insert operation to introduce new node, however you need to invoke select to prepare the data for insert

Updating/moving the node

moving the node requires one select and one update operation

Node removal

is done with single operation

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.

Getting all node descendants

There are two options to get all node descendants. One is classic through recursion:

second is using aggregation framework introduced in MongoDB 2.2:

Getting path to node

This operation is done with single call to database, which is advantage of this approach.

Indexes

Recommended index is putting index on ancestors

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 descendants 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 withRockMongo web shell.

Points of Interest

Please note, that MongoDB does not provide ACID transactions. This means, that for update operations split into separate update commands, your application should implement additional code to support your code specific transactions.

Formal advise from 10gen is following:

  • The Parent Reference pattern provides a simple solution to tree storage, but requires multiple queries to retrieve subtrees
  • The Child References pattern provides a suitable solution to tree storage as long as no operations on subtrees are necessary. This pattern may also provide a suitable solution for storing graphs where a node may have multiple parents.
  • The Array of Ancestors pattern — no specific advantages unless you constantly need to get path to the node

You are free to mix patterns (by introducing order field, etc) to match the data operations required to your application.

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