PHP/Mongo – Nested set model

Last time I created some structure for linking different elements from similar groups. This project needed high performance and easy way to get elements hierarchy, but changes are not often. After consideration I decided to implement nested set tree model to do this. All is based on PHP and use Mongo database and I would like to show you some basis operations with that. It can be helful in some cases, and that model is very efficient in read operations.

First: why nested set? Because it’s very fast, comfortable and easy to get data from elements tree and build hierarchy of any of them – with parents, childs, siblings. It isn’t perfect, because adding new elements isn’t as simple as in many other structures, and moving tree branches is somewhat complicated, but in this case it was no issue, because I did not need such functionality. I will not describe whole nested set model, you can find information about that on many websites, including Wikipedia. It may be similar to binary trees, but uses more data to put data in specific place in tree.

Second thing, we must check assumptions. I decided to store many data in each element, but redundancy in Mongo is “in definition” of this database, so I could do that. Nested set model required left and right id’s, but I also stored depth level in tree and direct parent objectId for each element. Because of that, many operations are much simpler than without such data – we can use not only sides id’s, but also objectId’s and find elements by their depth in hierarchy. First, check code for adding new element:

Where newElementId is relation to other collection… but we can also use here data or structure with data, it isn’t problem. This code allows you to use many different nested set tress in collection. I use standard MongoDB extension for PHP and create methods to get current collection, but it should be clear. Getting element by treeId and elementId should be also clear, so move to somthing more interesing – get data. We can add new elements and this “magic” code will build all three automatically – just use parent ids. But what about get parents, childs or sibling? Look here: