Hello
[
{
"$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": "$$array1_member.array2"
},
"in": {
"$let": {
"vars": {
"array2_member": {
"$arrayElemAt": [
"$$array2",
0
]
}
},
"in": "$$array2_member.comments"
}
}
}
}
}
}
}
}
}
}
]
Printed
{comments 10}
You changed the $let ,while trying it i guess and you did it
"vars": {
"array2": "$$array1.array2"
},
Where it was (previous query worked also, i think this edit above made it to now work)
"vars": {
"array2": "$$array1_member.array2"
}
Previous query i think worked also for the first data if you run it unchanged.
I sended you the same query for the new data,i didnt really changed anything just the names
of the new fields.
For the second thing,about updating one array,first method is fine,but you need to do some extra checks that i didnt do,i dindnt checked if the member was the last in the array
This works in all cases i think,edit the “index”: 0 , myarray with your field name,
and here i just add 10 to the member to update it, change the new_m bellow
"new_m": {
"$add": [
"$$m",
10
]
}
}
Query
[
{
"$addFields": {
"myarray": {
"$let": {
"vars": {
"index": 0
},
"in": {
"$let": {
"vars": {
"m": {
"$arrayElemAt": [
"$myarray",
"$$index"
]
},
"array_before": {
"$slice": [
"$myarray",
"$$index"
]
},
"array_after": {
"$cond": [
{
"$lt": [
"$$index",
{
"$subtract": [
{
"$size": "$myarray"
},
1
]
}
]
},
{
"$slice": [
"$myarray",
{
"$add": [
"$$index",
1
]
},
{
"$size": "$myarray"
}
]
},
[]
]
}
},
"in": {
"$let": {
"vars": {
"new_m": {
"$add": [
"$$m",
10
]
}
},
"in": {
"$concatArrays": [
"$$array_before",
[
"$$new_m"
],
"$$array_after"
]
}
}
}
}
}
}
}
}
}
]