mongodb获得最古老的动物地图/减少

时间:2011-08-07 08:25:16

标签: javascript mongodb node.js mapreduce

我从未尝试过map / reduce。

我如何获得每种动物中最古老的动物?

我的数据是这样的:

[
{
  "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": "cat",
  "age": 8,
  "id": "e"
},
{
  "cateory": "company",
  "type": "Internet",
  "age": 5,
  "id": "Facebook"
}
]

我正在使用node-mongodb-native。谢谢!

2 个答案:

答案 0 :(得分:3)

您的地图功能应如下所示:

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

还原功能:

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

  return {age: maxAge};
}

答案 1 :(得分:0)

这很简单:

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