Ali Al-ali
Ali Al-ali

Reputation: 229

How to Sort and limit result mapReduce in mongoDB

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()

Upvotes: 1

Views: 2396

Answers (1)

Alex P.
Alex P.

Reputation: 3171

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);

Upvotes: 2

Related Questions