My goal is to return a fully linked object that matches based on the root name of the object I feed in, and also filters the "Sub Sub Objects" at the same time.
So given the below example schema:
1. Root Object Collection
[ { "_id": ObjectId("AAA1"), "name": "rootObj1", "subObjects": [ ObjectId("BBB1"), ObjectId("BBB2") ] }, { "_id": ObjectId("AAA2"), "name": "rootObj2", "subObjects": [] } ]
2. Sub Object Collection
[ { "_id": ObjectId("BBB1"), "name": "subObjectName1", "subSubObjects": [ ObjectId("CCC1"), ObjectId("CCC2") ] }, { "_id": ObjectId("BBB2"), "name": "subObjectName2", "subSubObjects": [ ObjectId("CCC2") ] } ]
3. Sub Sub Object Collection
[ { "_id": ObjectId("CCC1"), "name": "nameToFind" }, { "_id": ObjectId("CCC2"), "name": "someOtherName" } ]
My goal is to return something like the below if I passed in that I want 'rootObj1' and I only want the subSubObjects that have the name 'nameToFind' (or something similar to the below, i don't care if the _id are still in the objects, just the idea that things are linked together)
Goal Result
{ "name": "rootObj1", "subObjects": [ { "name": "subObjectName1", "subSubObjects": [ {"name": "nameToFind"} ] }, { "name": "subObjectName2", "subSubObjects": [] } ] }
I found a lot of helpful posts showing off $lookup, $unwind, $lookup (using the pipeline feature), and then using group/project or something to assemble it. And while I am able to use lookup to find the values I end up with something like the below and have trouble assembling it.
So I was trying to run something like this:
rootCollection.aggregate([
{ "$match": {
"name" : "rootObject1",
}},
{ "$lookup": {
"from": "subObject",
"localField": "subObjects",
"foreignField": "_id",
"as": "subObjects"
}
},
{ "$lookup": {
"from": "subSubObjects",
"localField": "subObjects.subSubObjects",
"foreignField": "_id",
"as": "subSubObjects"
}
},
])
Which ends up as something like the below, but I don't really understand how to filter the subSubObjects and then somehow merge it all back together into one structure.
[ { "_id": {"$oid": "AAA1"}, "name": "rootObject1", "subObjects": [ {"$oid": "BBB1")}, {"$oid": "BBB2")} ] }, "subObjects": [ { "_id": {"$oid": "BBB1"}, "name": "subObjectName1", "subSubObjects": [ {"$oid": "CCC1")}, {"$oid": "CCC2")}) ] }, { "_id": {"$oid": "BBB2"}, "name": "subObjectName2", "subSubObjects": [ {"$oid": "CCC1")}, {"$oid": "CCC2")}) ] }, ], "subSubObjects": [ { "_id": {"$oid": "CCC1"}, "name": "nameToFind", }, { "_id": {"$oid": "CCC2"}, "name": "someOtherName", }, ] ]