MongoDB can store subdocuments:
Node { "value" : "root" "children" : [ { "value" : "child1", "children" : [ ... ] }, { "value" : "child2", "children" : [ ... ] } ] }
However, I do not recommend using subdocuments for tree structures or something rather complicated. Subdocuments are not first-level citizens; they are not elements of the collection.
For example, suppose you want to quickly find nodes with a given value. Through the value index, this search will be fast. However, if the value is in a subdocument, it will not be indexed because it is not the value of a collection item.
Therefore, it is usually better to serialize manually and instead keep a list of identifiers:
Node { "_id" : ObjectId("..."), "parentId" : ObjectId("..."), // or null, for root }
You will need to manually serialize to get the corresponding item IDs.
Tip Suppose you want to get the whole branch of a tree. Instead of storing only the direct parent identifier, you can save all the ancestor identifiers:
"ancestorIds": [id1, id2, id3]
source share