I'm currently facing a challenge in implementing a query that is straightforward in functional programming languages but proving to be tricky in a Mongo Query.
The term I've come across for this scenario is "Max Hold":
- I attempted to use a mongo aggregation query and utilize $function, however, it seems to only apply to calculations of the map-reduce kind (struggling to retain intermediate values within the documents being passed on)
input:
[
{ "key": 1, "value": 10 } ,
{ "key": 2, "value": 11 } ,
{ "key": 3, "value": 9 } ,
{ "key": 4, "value": 12 }
]
output:
[
{ "key": 1, "value": 10, "prefix_max_val": 10 } ,
{ "keyquot;: 2, "value": 11, "prefix_max_val": 11 } ,
{ "keyquot: 3, "value": 9, "prefix_max_val": 11 } ,
{ "key&qout;: 4, "value": 12, "prefix_max_val": 12 }
]
In Javascript
(or any other general-purpose programming language), my approach would resemble something like this (an algorithm with linear time complexity):
function(input) {
let result = [];
let curr_max = 0;
for (let i=0; i<input.length; i++) {
result[i] = Math.max(curr_max, input[i]);
curr_max = result[i];
}
return result;
}
Thank you :)
EDIT:
- I am operating with Mongo v0.39