mongodb获取最古老的动物map/reduce

发布于 2024-11-28 13:33:49 字数 555 浏览 0 评论 0原文

我从未尝试过映射/归约。

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

我的数据是这样的:

[
{
  "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。谢谢!

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最近可好 2024-12-05 13:33:49

你的映射函数应该是这样的:

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};
}

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};
}
瑕疵 2024-12-05 13:33:49

这很简单:

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

It's pretty simple:

collection.find({type : 'animal'}).sort({animal: -1}).limit(1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文