gpt4 book ai didi

javascript - 按最高计数聚合

转载 作者:行者123 更新时间:2023-11-30 12:39:35 26 4
gpt4 key购买 nike

如何使用聚合框架按最高计数聚合结果?

{
"type": "dog",
"name": "buddy",
"count": 67
},
{
"type": "dog",
"name": "buddy",
"count": 34
},
{
"type": "dog",
"name": "tucker",
"count": 17
},
{
"type": "dog",
"name": "tucker",
"count": 52
},
{
"type": "cat",
"name": "gizmo",
"count": 11
}

我正在尝试汇总上面的结果,所以如果 dog 具有相同的 name 我想获得计数最高的那个。所以它看起来像:

{
"type": "dog",
"name": "buddy",
"count": 67
},
{
"type": "dog",
"name": "tucker",
"count": 52
},
{
"type": "cat",
"name": "gizmo",
"count": 11
}

我已经尝试为此使用 $group,但我真的不知道如何根据最高计数区分结果。

最佳答案

count 降序排列所有文档,然后从typename 的每个分组中取出第一个count :

db.test.aggregate([
{$sort: {count: -1}},
{$group: {_id: {type: '$type', name: '$name'}, count: {$first: '$count'}}}
])

输出:

{
"result" : [
{
"_id" : {
"type" : "cat",
"name" : "gizmo"
},
"count" : 11
},
{
"_id" : {
"type" : "dog",
"name" : "tucker"
},
"count" : 52
},
{
"_id" : {
"type" : "dog",
"name" : "buddy"
},
"count" : 67
}
],
"ok" : 1
}

关于javascript - 按最高计数聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936028/

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