gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:18:33 27 4
gpt4 key购买 nike

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

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

我的数据是这样的:

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

最佳答案

您的 map 函数应如下所示:

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

关于javascript - mongodb获取最古老的动物map/reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6971604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com