gpt4 book ai didi

mongodb - 使用 Mongo 聚合框架对数组进行分组操作

转载 作者:可可西里 更新时间:2023-11-01 09:15:47 25 4
gpt4 key购买 nike

我正在使用 mongodb 2.2。我想使用新的聚合框架对我的文档进行查询,但元素是数组。

这里是我的 $project 结果的例子:

{ 
"type" : [
"ads-get-yyy",
"ads-get-zzz"
],
"count" : [
NumberLong(0),
NumberLong(10)
],
"latency" : [
0.9790918827056885,
0.9790918827056885
]
}

我想按类型分组,所以“ads-get-yyy”要知道计数的平均值是多少,延迟的平均值是多少。

我想要类似于下一个查询的东西,但它在每个数组的元素内部起作用:

db.test.aggregate(
{
$project : {
"type" : 1,
"count" : 1,
"latency" : 1
}
},{
$group : {
_id: {type : "$type"},
count: {$avg: "$count"},
latency: {$avg: "$latency"}
}
});

最佳答案

我也在学习新的 AF,但我认为您需要先$unwind 类型,以便您可以按它们分组。所以像这样:

db.test.aggregate({
$project : {
"type" : 1,
"count" : 1,
"latency" : 1
}
},{
$unwind : "$type"
},{
$group : {
_id: {type : "$type"},
count: {$avg: "$count"},
latency: {$avg: "$latency"}
}
});

关于mongodb - 使用 Mongo 聚合框架对数组进行分组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506904/

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