O
O
Ockonal2014-08-20 17:14:46
MongoDB
Ockonal, 2014-08-20 17:14:46

How to make a limit in mapreduce?

Hello, I'm using mongodb + built-in implementation of mapreduce.
The data looks like this:
{ obj: integer, likes: integer}, ...
I need to get 2 documents for each unique obj type with the maximum number of likes .
Let's say we have the following data:

1=>124, 1=>20, 1=>70, 1=>150,
  3 => 500, 3=>499, 3=>0

As a result, I need to get:
1=>150, 1=>124,
3=>500, 3=>499

This is what the map function looks like:
mapFunc = Code('function() { 
   emit(this.gid, { likes: this.likes, obj : this._id });
}')

And reduce:
reduceFunc = Code('function(key, values) { 
   var likesCount = -1;
   var selectedId = -1;
   values.forEach(function(value) {
      if (value["likes"] > likesCount)
      {
         likesCount = value["likes"];
         selectedId = value["obj"];
      }
   });
   return {likes: likesCount, obj: selectedId};
}')

In fact, this example will return what I need, but 1 record per unique obj , this could be achieved with the usual aggregation framework.
I just can't figure out how to take the last 2 posts with the maximum number of likes in this approach .

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question