1

I have something like:

mongoTemplate.mapReduce("myCollection", MAP_FUNC, REDUCE_FUNC, KeyValuePair.class);

Then the result looks like:

[
{id: "1", count: 5},
{id: "2", count: 20},
{id: "3", count: 9},
{id: "4", count: 3}
]

How can I sort this array like:

[

{id: "2", count: 20},
{id: "3", count: 9},
{id: "1", count: 5},
{id: "4", count: 3}
]

and after that limit result to 5.

There is a sort option in MongoDB mapReduce, but I cannot find it in class org.springframework.data.mongodb.core.mapreduce.MapReduceOptions from Spring Data MongoDB.

Jaiwo99
  • 9,687
  • 3
  • 36
  • 53
  • 1
    @Stennie, it is not a duplicate! it is about 'Spring-Data', not only mongo DB!!!! Please read my question exactly!! – Jaiwo99 Jan 18 '16 at 12:26
  • As per the [MongoDB, MapReduce and sorting](http://stackoverflow.com/questions/12015064/mongodb-mapreduce-and-sorting) discussion (and the MongoDB manual), the `sort` option in mapReduce only applies to input sort order not the result sort order. This is an expected part of the server implementation and unrelated to Spring Data. If you want to sort a result set you need to use an explicit sort order in your find query (by `count`). If your processing can be expressed using the Aggregation Framework, you will likely find that a more performant approach for processing, sorting, and limiting. – Stennie Jan 18 '16 at 12:58
  • Your Map/Reduce query would require writing data to an output collection and then doing an additional find() query sorting by `count` (descending) with a limit of 5 results. If you are just doing totals by a unique id (or collection of attributes) this would be a straightforward query in aggregation: `$group` by unique values with a `$sum` for each grouping, then `$sort` by count (descending), and `$limit` to 5 results. See: [Aggregation examples](https://docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set/). – Stennie Jan 18 '16 at 13:07
  • Hi @Stennie, thanks for the answer, actually the aggregation framework doesn't work with my case, because I am mapping with a DB-REF, from my understanding that the aggregation framework doesn't work with DB-REF, that's why i'm doing mapReduce ;) – Jaiwo99 Jan 18 '16 at 13:21

0 Answers0