I have a mongo db like this:
db.templates.insertMany( [
{ _id: 1, uuid: "1", name: "t1", related_templates: [ "2", "2" ] },
{ _id: 2, uuid: "2", name: "t2", related_templates: [ "3", "3" ] },
{ _id: 3, uuid: "3", name: "t3", related_templates: [ "4", "4" ] },
{ _id: 4, uuid: "4", name: "t4"},
] )
As you can see, the data represents a tree structure, but supports duplicate references to the same child node. I'm trying to recursively fetch the whole tree starting from t1, including duplicate references.
The result would look like this:
{
"_id" : 1,
"uuid" : "1",
"name": "t1",
"related_templates" : [
{
"_id" : 2,
"uuid" : "2",
"name" : "t2",
"related_templates" : [
{
"_id" : 3,
"uuid" : "3",
"name" : "t3",
"related_templates" : [
{
"_id" : 4,
"uuid" : "4",
"name" : "t4"
},
{
"_id" : 4,
"uuid" : "4",
"name" : "t4"
}
]
},
{
"_id" : 3,
"uuid" : "3",
"name" : "t3",
"related_templates" : [
{
"_id" : 4,
"uuid" : "4",
"name" : "t4"
},
{
"_id" : 4,
"uuid" : "4",
"name" : "t4"
}
]
}
]
},
...(t2 repeats here)
]
}
The solution suggested on the Mongo website is here: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#std-label-unwind-example. If there are no duplicate references, this solution works great, with a bit of modification even allowing for recursive lookups as well. However, in my situation I need to preserve duplicate lookups
I've also considered the legacy solution of using unwind + group. That solution does preserve duplicates, but I haven't figured out how to use it recursively.
I've also considered using the solution on the mongo website to fetch without duplicates, then doing something with a map to attach the fetched data to the original related_templates array. I think this would work, but it doesn't seem very elegant.
Is there an elegant/easier solution to do this that I'm missing?