So I’m trying to increment a number in an array that is situated in an object which is situated in an array Let’s say today’s date is 05/03/2023, which is found in the object so it will just increment the second number in the array
[{
key: "test",
numbers: [
0,
0,
0,
{
"05/03/2023": [ 0,5,0 ]
}
]
}]
So in the case above the result from the query will be:
[{
key: "test",
numbers: [
0,
0,
0,
{
"05/03/2023": [ 0,6,0 ]
}
]
}]
But if our collection is:
[{
key: "test",
numbers: [
0,
0,
0,
{}
]
}]
In this case it will need to create the array and this is how the result should look
[{
key: "test",
numbers: [
0,
0,
0,
{
"05/03/2023": [ 0,1,0 ]
}
]
}]
This is what I tried but doesn’t work $addFields sets everything in the numbers array and I’m confused
db.collection.update({},
[
{
$addFields: {
"numbers.3.04/03/2023": {
$cond: {
if: { $isArray: "numbers.3.04/03/2023" },
then: {
$concatArrays: [ { $slice: [ "numbers.3.04/03/2023", 0, 1 ] },
[ { $add: [ { $arrayElemAt: [ "numbers.3.04/03/2023", 1 ] }, 1 ] } ],
{$slice: [ "numbers.3.04/03/2023", 2, 1 ] }
]
},
else: [ 0, 1, 0 ]
}
},
}
},
])