joe
joe

Reputation: 1911

MongoDB map reduce producing strange result

I am implementing a simple 'get max value' map reduce in MongoDB (c# driver). For my tests I have 10 items in a collection with int _id = 1 to 10.

My map and reduce are as follows:

var map = "function() {emit('_id', this.Id);}";
var reduce = "function(key, values) {var max = 1; for (id in values) {if(id>max) {max=id;}} } return max;}";

When I run however I get the result 9, strange!!

I think that the map is outputting a string, and thus the compare is not working as desired. Any help would be great

Upvotes: 0

Views: 174

Answers (1)

cubbuk
cubbuk

Reputation: 7920

Reduce function won't run if the values contain only one item. If all the ids are unique and your key in the map is only that id, reduce phase won't work because of a design issue (for improving performance). If you need to change the format of your reduce output, you should use finalize method. Or just take a look at the aggregation framework which provides quite useful tools for playing with data.

Check the jira

jira.mongodb.org/browse/SERVER-5818

If you are just trying to get familiar with map reduce I would suggest to try different scenarios where using map-reduce really makes sense

Cheers

Upvotes: 1

Related Questions