Amit
Amit

Reputation: 34725

Mongodb: Store a tree as one nested document or store one document per node?

I am using MongoDB and I want to store various trees in it.

Question: Which way is recommended for storing trees?

Here are the operations that I want to perform on my data:

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;
}

Upvotes: 2

Views: 2604

Answers (1)

Derick
Derick

Reputation: 36774

It looks like you are going to lots of operations in different levels of nested nodes in the tree. Although MongoDB can store a structure like you describe, it is not very good at allowing you to do update at lots of nested levels.

Therefore I would recommend you to store each node as it's own document, and look at where you store the parent-child relations. Remember to optimise the schema for data operations. I'd go with your "way 1" in this case. If you would not have to change the tree a lot, and you have say 1000x more read than write operations to the tree, then you could consider using "way 2" and just deal with the extra work it takes to update the nodes at a few levels deep.

Upvotes: 5

Related Questions