MongoDB tree model: Get all ancestors, Get all descendants

I have an arbitrary tree structure.

Example data structure:

root
  |--node1
  |     |--node2
  |     |     |--leaf1
  |     |
  |     |--leaf2
  |
  |--node3
        |--leaf3

Each node and leaf have 2 properties: idand name.


Important queries:

1.:The sheet identifier is given. The request should return all the way from the root to this sheet with all the properties of node idand name.

It doesn’t matter if the return value is a sorted array of nodes or if it is an object where the nodes are nested.

Example: If the set idof leaf2, the query should return: root(id, name), node1(id, name), leaf2(id, name).


2.:For any node id: Get the full (auxiliary) tree. Here it would be nice to get one object where each node has an array children.


, :

1.: JSON, : , . id , MongoDB . , ids, .

2.: , , node , node ids:

{
  id: ...,
  name: ...,
  ancestors: [ rootId, node1Id, ... ]
}

, 2 , root node , .

:

2.: ?

: find({ancestors:"myStartingNodeId"}). , , .

, ?

!

+6
3

, . . (, ) .

{
  id: "...",
  ancestors: ["parent_node_id", ..., "root_node_id"], // order is important!
  children: ["child1_id", "child2_id", ...]
}

:

  • node

  • , - /// node

  • . children

:

  • ID: findOne({ id: "..." })

  • : findOne({ children: "..." })

  • : Get by ID, ,

  • : find({ 'ancestors.0': "..." })

  • : find({ ancestors: "..." })

  • x : find({ $and: [ {ancestors: "..."}, {ancestors: {$size: x}} ] })

:

  • .

  • (, MongoDB).

  • insert 2 .

  • .

+2

MongoDB , .

, 2. ( ), find({ancestors:"myStartingNodeId"}) / .

- , _id ( - ) , 'root.node1.node2'. , () _id.


: . , MongoDB: MongoDB

+3

Source: https://habr.com/ru/post/1599682/


All Articles