Looking to calculate the average of cities in each state using the Reduce Function in mongoDB, but encountering an issue where only one correct result is obtained while rest return as 'nan'.
Below is the map function:
function map(){
key = {state : this.state};
values = { numberOfCities:1, statePop: this.pop};
emit(key, values)}
And the reduce function:
function reduce(key , values){
numberOfCities = 0.0;
statePop = 0.0;
avg = 0.0;
for (i in values){
numberOfCities += values[i].numberOfCities;
statePop += values[i].statePop;
avg = statePop/numberOfCities;
}
return avg}
The issue lies in returning statePop/numberOfCities leading to nan value, while returning statePop with numberOfCities provides the correct number.
Error Scenario:
Inspecting the json file (a single line from the file):
{ "_id" : "20002", "city" : "WASHINGTON", "loc" : [ -76.990055, 38.902365 ], "pop" : 56756, "state" : "DC" }