For the first one - good catch! That was actually just a typo in my post here. But I found out what the real problem was. The last condition.
"in": "$$array2.comments"
Should be:
"in": "$$array2_member.comments"
Final working query is here:
db.aggregate([
{ $match: { "$expr": { "$eq": [ "$_id", "ROOT_DOCUMENT_ID" ] } } },
{
$project: {
"_id": 0,
"comments": {
$let: {
"vars": {"array1": "$$ROOT.array1" },
"in": {
$let: {
"vars": {
"array1_member": {
$arrayElemAt: [
{
$filter: {
"input": "$$array1",
"as": "m",
"cond": {
$eq: [
"$$m._id",
"ARRAY1_B"
]
}
}
},
0
]
}
},
"in": {
$let: {
"vars": {
"array2_member": "$$array1_member.array2"
},
"in": {
$let: {
"vars": {
"array2": {
$arrayElemAt: [
"$$array2",
0 // This is the index I want
]
}
},</pre>
"in": "$$array2_member.comments"
}
}
}
}
}
}
}
}
}
}
])
This gives the desired output.
For the second query, I was trying to work with that but I don’t see array1 or array2 being referenced anywhere or matched. I don’t really see how to fit that into my case.
With the following data:
{
"_id" : "ROOT_DOCUMENT_ID",
"array1" : [
{
"_id" : "ARRAY1_A",
"array2" : [
{
"_id" : "ARRAY2_A",
"comments" : 0
}
]
},
{
"_id" : "ARRAY1_B",
"array2" : [
{
"_id" : "ARRAY2_A",
"comments" : 10
},
{
"_id" : "ARRAY2_B",
"comments" : 20
},
{
"_id" : "ARRAY2_C",
"comments" : 30
}
]
}
]
}
The only information I have is: _id (root document ID), array1._id, and the index of array 2.
Appreciate the help again!