MapReduce Functions

Hello! I am very new to MongoDB.
I am trying to write a map reduce function (not an aggregation):

So far I have:
var mapHorse1 = function(){
var key = this.shows; if(this.shows <50) emit(key,1);};

I need to show the number of horses who have gender = female, and less than 50 shows - but I don’t know how to add in the gender filter to the above function. Can someone please assist?
Many thanks

Hey Kristen, welcome to the MongoDB community

Try this:

var mapHorse1 = function() {
    var key = this.shows;
    if (this.shows < 50 && this.gender === 'female') {
        emit(key, 1);
    }
};
var reduceFunction1 = function(key, values) {
    return Array.sum(values);
};
db.coll.mapReduce(
    mapHorse1,
    reduceFunction1,
    {
        out: "map_reduce_result"  // Name collection out
    }
)

Thank you so much! I’ll give that a go!

You’re welcome, I’m at your disposal and if your problem has been resolved, leave this topic as resolved so that other people can benefit from it!

Hi Samuel - sorry that did not work. Whilst there were no errors - when I called the functions, no results / data displayed.

Hi Samuel - I have worked it out - I just had to make one very small change to the map function! Thank you so much for your help!

It would be interesting and fair to all to see the final working map function.

Hiya! Apologies - yes of course!
I just had to change the var key assignment to “this.name”, in the map function.
Thank you so much for your help!

var mapHorse1 = function() {
var key = this.name;
if (this.shows < 50 && this.gender === ‘female’) {
emit(key, 1);
}
};

2 Likes