开发者

mongodb getting the oldest of animals map/reduce

开发者 https://www.devze.com 2023-03-26 05:31 出处:网络
I\'ve never tried map/reduce. How would I get the oldest of each type of animal? My data is like this: [

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

精彩评论

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