https://www.mongodb.com/docs/manual/tutorial/model-tree-structures-with-parent-references/ describes 5 ways to model tree-like structures in MongoDB, and recommends to use $graphlookup to traverse the tree.
All examples of $graphlookup return a flat array of the referenced documents tho, and it's not quite clear how should I use it to return the tree structure of subdocuments within subdocuments within subdocuments etc.
I am flexible with data structure as long as I can get each document by _id regardless of how far from the root it is, and retrieve the whole tree of dereferenced/embedded documents:
[
{
"_id": "a",
"label": "Cat",
"children": [
{
"_id": "b",
"label": "Big cat",
"children": [
{
"_id": "c",
"label": "Lion"
},
{
"_id": "d",
"label": "Jaguar"
},
{
"_id": "e",
"label": "Tiger"
}
]
},
{
"_id": "f",
"label": "Small cat",
"children": [
{
"_id": "g",
"label": "Bay cat"
},
{
"_id": "h",
"label": "Desert lynx"
},
{
"_id": "i",
"label": "Leopardus",
"children": [
{
"_id": "j",
"label": "Guina"
},
{
"_id": "k",
"label": "Tigrillo"
},
{
"_id": "l",
"label": "Ocelot"
}
]
},
{
"_id": "m",
"label": "Lynx"
},
{
"_id": "n",
"label": "Felis",
"children": [
{
"_id": "o",
"label": "Jungle cat"
},
{
"_id": "p",
"label": "Sand cat"
},
{
"_id": "q",
"label": "Wildcat",
"children": [
{
"_id": "r",
"label": "African wildcat"
},
{
"_id": "s",
"label": "European wildcat"
},
{
"_id": "t",
"label": "Domestic cat"
}
]
}
]
}
]
}
]
}
]
How should I store all these animals, and what pipeline operators can recursively populate the nested structure?
I have created the flat list of these cats in https://mongoplayground.net/p/7D8SgIh-85W to play with.