1

I am new with MongoDB and Map Reduce. I have cities, states and population for each city.

The question is to find the largest state population. I have done a query to get all states with their population but I could not get only the max state with its population

Map

map = function(){emit(this.state , this.pop)}

Reduce

reduce = function (key, values) {
    var max = 1;
    var pop = Array.sum(values);

    if (pop > max) max = pop;

    return pop;
}

to run it

 db.zipcodes.mapReduce(map , reduce , {out:'result1'}).find()

1 Answer 1

2

Not sure if you have figured it out by now.

Here some test data:

{ 
    "state" : "Alabama", 
    "cities" : "Auburn", 
    "pop" : NumberInt(10)
}
{ 
    "state" : "New York", 
    "cities" : "New York City", 
    "pop" : NumberInt(105)
}
{ 
    "state" : "Alabama", 
    "cities" : "Birmingham", 
    "pop" : NumberInt(20)
}

After the mapReduce is through you would get these results in "result1":

{ 
    "_id" : "Alabama", 
    "value" : 30.0
}
{ 
    "_id" : "New York", 
    "value" : 105.0
}

By sorting on the value field with -1 (descending) you would get the results from the highest to the lowest. Then if you limit your result set, you could get exactly the first one which is also the one with the highest population.

Here is the complete mapReduce:

db.zipcodes.mapReduce(
function() {
    emit(this.state, this.pop)
}, 
function(key, values) {
    var max = 1;
    var pop = Array.sum(values);

    if(pop > max) max = pop;

    return pop;
}, 
{
    out: 'result1'
}
).find().sort({value: -1}.limit(1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.