How to represent a tree structure in NoSQL

database-designmongodbnode.jsnosql

I'm new to NoSQL and have been playing around with a personal project on the MEAN stack (Mongo ExpressJs AngularJs NodeJs). I'm building a document editor of sorts that manages nodes of data. Each document is actually a tree.

I have a CRUD api for documents, to create new trees and a CRUD api for nodes in a given document.

Right now the documents are represented as a collection that holds everything, including nodes. The children parent relationship is done by ids. So the nodes are an map by id, and each node has references to what nodes are their children. I chose this "flat" approach because it is easier to get a node by id from a document.

Being used to having a relation table between nodes and documents, a relation table between nodes and children nodes I find it a bit weird that I have to save the entire "nodes" map each time I update a node.

Is there a better way to represent such a data type in NoSQL?

Best Answer

You have a number of options when representing a tree structure with MongoDB. Here are five "patterns" that you could apply (link to details at the end).

  • The Child References pattern stores each tree node in a document; in addition to the tree node, document stores in an array the id(s) of the node’s children.
  • 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.
  • The Array of Ancestors pattern stores each tree node in a document; in addition to the tree node, document stores in an array the id(s) of the node’s ancestors or path.
  • The Materialized Paths pattern stores each tree node in a document; in addition to the tree node, document stores as a string the id(s) of the node’s ancestors or path.
  • The Nested Sets pattern stores each tree node in a document; in addition to the tree node, document stores the id of node’s parent, the node’s initial stop in the left field, and its return stop in the right field.

This tutorial in the MongoDB tutorial discusses the pros and cons of each pattern: http://docs.mongodb.org/manual/tutorial/model-tree-structures/

Related Topic