开发者

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
  }
}
开发者_StackOverflow社区

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜