开发者

mongodb getting the oldest of animals map/reduce

I've never tried map/reduce.

How would I get the oldest of each type of animal?

My data is like this:

[
{
  "cateory": "animal",
  "type": "cat",
  "age": 4,
  "id": "a"
},
{
  "cateory": "animal",
  "type": "bird",
  "age": 3,
  "id": "b"
},
{
  "cateory": "animal",
  "type": "cat",
  "age": 7
  "id": "c"
},
{
  "cateory": "animal",
  "type": "bird",
  "age": 4,
  "id": "d"
},
{
  "cateory": "animal",
  "type": "ca开发者_高级运维t",
  "age": 8,
  "id": "e"
},
{
  "cateory": "company",
  "type": "Internet",
  "age": 5,
  "id": "Facebook"
}
]

I'm using node-mongodb-native. Thanks!


Your map function should look something like this:

map = function() {
  emit({type: this.type}, {age: this.age});
}

And the reduce function:

reduce = function(key, values) {
  maxAge = 0;
  values.forEach(function(v) {
    if (maxAge < v['age']) {
       maxAge = v['age'];
    }
  });

  return {age: maxAge};
}


It's pretty simple:

collection.find({type : 'animal'}).sort({animal: -1}).limit(1);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜