'Invalid Reference $$this for mongo array reduce arithmetic operation in java
First of all here is project before reduce
How you can see there is a list called "1" with 3 fields (zone, duration, type)
I'm trying to reduce it and get the total sum of durations on 1_total_duration
But throws Invalid Reference for $$this.duration
Already tried to use ArrayOperators.Reduce.Variable.THIS.referringTo("duration").getName()
But since StringOperators.Concat works (converting first duration to string) I'm wondering why ArithmeticOperations throws "Invalid Reference '$$this.duration'!"
Don't want to use unwind since i will have multiple lists like "1" to do the same reduce process
Solution 1:[1]
Not a perfect solution but I managed to get what i needed like this
STEPS:
1- Convert "duration" to String
2- Reduce Array to a concatenated String separated with ","
AggregationExpression reduce = StringOperators.Concat
.valueOf("$$value")
.concat(",")
.concat("$$this.duration");
operations.add(project("1")
.and(ArrayOperators.Reduce.arrayOf("1")
.withInitialValue("")
.reduce(reduce))
.as("1_duration_str_array")
);
3- Remove first "," (initial value is "" and is concatenated)
operations.add(project("1_duration_str_array")
.and(StringOperators.Substr.valueOf("1_duration_str_array").substring(1))
.as("1_duration_str_array")
);
4- Split String with "," to get Array
operations.add(project("1_duration_str_array")
.and(StringOperators.Split.valueOf("1_duration_str_array").split(","))
.as("1_duration_array_str")
);
5- Map elements to convert back to Double
operations.add(project("1_duration_array_str")
.and(VariableOperators.Map
.itemsOf("$1_duration_array_str")
.as("d")
.andApply(ConvertOperators.Convert
.convertValueOf("$d").to("double")))
.as("1_duration_array")
);
6- Sum operation on Array
operations.add(project("1_duration_array")
.and(AccumulatorOperators.Sum.sumOf("1_duration_array"))
.as("1_total_duration")
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |



