I have an arbitrary tree structure.
root
|--node1
| |--node2
| | |--leaf1
| |
| |--leaf2
|
|--node3
|--leaf3
Each node and leaf has 2 properties: id
and name
.
1.:
A leaf id is given. The query should return the whole path from root to that leaf, with all node's id
and name
properties.
It's not important if the return value is an sorted array of nodes or if it's an object where the nodes are nested.
Example: If the id
of leaf2
is given, the query should return: root(id, name), node1(id, name), leaf2(id, name)
.
2.:
Given any node id
: Get the whole (sub)tree. Here it would be nice to retrieve a single object where each node has a children
array.
1.:
First I tried to simply model the tree as a single JSON document, but then the query would become impossible: There's no way to find out at which nesting level the leaf is. And if I knew the whole path of id
s from root to the leaf, I'd had to use a projection with multiple positional operators and that's not supported by MongoDB at the moment. Additionally it's not possible to index the leaf ids
because the nesting can be infinite.
2.:
Next idea was to use a flat data design, where each node has an array which contains the node's ancestor ids
:
{
id: ...,
name: ...,
ancestors: [ rootId, node1Id, ... ]
}
This way I'd have to do 2 queries, to get the whole path from root to some node or leaf, which is quite nice.
If I choose data model 2.
: How can I get the whole tree, or a subtree?
Getting all descendants is easy: find({ancestors:"myStartingNodeId"})
. But those will of course be not sorted or nested.
Is there a way using the aggregation framework or a completely different data model to solve this problem?
Thank you!
MongoDB allows various ways to use tree data structures to model large hierarchical or nested data relationships. Presents a data model that organizes documents in a tree-like structure by storing references to "parent" nodes in "child" nodes.
MongoDB is not a graph database and doesn't provide graph traversal operations, so there is no direct solution.
You can use data model you have described in point 2. (nodes with ancestor list), the query find({ancestors:"myStartingNodeId"})
and sort/nest the results in your application code.
Another possibility is to use data model where _id
(or some other field) represents full path, for example 'root.node1.node2'
. Then graph queries can be transformed to substring queries and correct ordering can be achieved (I hope) just by sorting by this _id
.
Update: btw. there are some tree structure patterns described in MongoDB docs: Model Tree Structures in MongoDB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With