So for the first part, here’s my sample data (I changed count to comments, because that’s the real field):
{
"_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
}
]
}
]
}
When I run the following find:
db.aggregate([
{ $match: { "$expr": { "$eq": [ "$_id", "ROOT_DOCUMENT_ID" ] } } },
{
$project: {
"_id": 0,
"comments": {
$let: {
"vars": {"array1": "$$ROOT.array1" },
"in": {
$let: {
"vars": {
"array1_element": {
$arrayElemAt: [
{
$filter: {
"input": "$$array1",
"as": "m",
"cond": {
$eq: [
"$$m._id",
"ARRAY1_B"
]
}
}
},
0
]
}
},
"in": {
$let: {
"vars": {
"array2": "$$array1.array2"
},
"in": {
$let: {
"vars": {
"array2": {
$arrayElemAt: [
"$$array2",
0 // This is the index I want
]
}
},
"in": "$$array2.comments"
}
}
}
}
}
}
}
}
}
}
])
It returns:
{
comments: [10, 20, 30]
}
It returns the same thing even when I change the index to 1 or 2. What I’m expecting is:
{
comments: 10
}
And for the 3 methods - is method #3 the best, since method 1 doesn’t allow me to update at the first and last index?