【问题标题】:mongodb getting the oldest of animals map/reducemongodb 获得最古老的动物地图/减少
【发布时间】:2011-08-07 08:25:15
【问题描述】:

我从未尝试过 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。谢谢!

【问题讨论】:

标签: javascript mongodb node.js mapreduce


【解决方案1】:

您的地图函数应该如下所示:

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

还有reduce函数:

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

  return {age: maxAge};
}

【讨论】:

  • 只有在 this.category == 'animal' 时才在 map 函数中发出一些东西
  • 此外,map-reduce 命令接受可用于过滤的query 参数。如果您在type 上有一个索引,那么query 参数将使您免于在多个文档上运行map()
  • @Gates VP 是的,谢谢,终于在测试中找到了查询参数。没有文档的人太可怕了。
【解决方案2】:

很简单:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2020-08-05
    • 1970-01-01
    • 2021-06-05
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多