Kevin
Kevin

Reputation: 958

Help with map reduce in MongoDB

I'm struggling to get a firm grasp of how map reduce works and when to use it. I'm getting some random results that just isn't making sense, but maybe my understanding of mapreduce in wrong?

Here's an example of what I am doing.

I have a collection of over 15000 uk towns with the following structure;

{
  "_id" : ObjectId("4e234105e138231a7f000004"),
  "county" : "Powys",
  "name" : "Abbey-Cwmhir",
  "location" : {
    "latitude" : 52.3298355191946,
    "longitude" : -3.39230306446552
  }
}

Each county has many towns, and I would like to get a new collection with the following structure for each county;

{
  "_id" : "Powys",
  "towns" : [
    {
      "name" : "Abbey-Cwmhir",
      "loc" : [52.3298355191946, -3.39230306446552]
    },
    //.. etc.
  ]
}

So, I guess map reduce is an ideal candidate for this right? If it is, how what would be the correct map and reduce functions?

Upvotes: 0

Views: 256

Answers (1)

Eugen Constantin Dinca
Eugen Constantin Dinca

Reputation: 9130

As a starting point you could use something like this:

Map function

function() {
  emit( this.county,{ 
          towns: [ 
            { 
              name: this.name, 
              loc: this.location 
            }
          ]
        } ); 
}

Reduce function

function(key, values) {
  result = { towns: [] }; 
  values.forEach( 
    function( townsgroup ) {
      townsgroup.towns.forEach( 
        function( town ) {
          result.towns.push( town );
        });
    });
  return result;
}

Thank you dcrosta for the correction.

Upvotes: 2

Related Questions