I am using MongoDB and I want to store various trees in it.
One way of storing tree is to store each node as a document with references to its children/parent/ancestors (as mentioned here)
Other way of storing it is to store whole tree as one document with children as sub-documents. e.g.
tree : { "title" : "root", "children" : [ { "title" : "node_1", "children" : [ ... ] }, { "title" : "node_2", "children" : [ ... ] } ] }
Question: Which way is recommended for storing trees?
Here are the operations that I want to perform on my data:
- Add a node
- Delete a node
- Update a node
- Get the json of whole tree
As I am planning to show this tree on UI using JsTree(you can recommend a better alternative to JsTree), which expects json data in nested format (way 2), I thought of storing the data in the same way instead of way 1.
If I store the json data in the db in way 1, then I will have to map a java object for each document/node and then manually create a tree object in java by pointing each parent to its corresponding children and then convert that java-tree-object back to json to get that nested json.
Jave object for each node looks like:
class Node {
private String title:
private List<Node> children;
}