gpt4 book ai didi

arrays - 蒙戈聚合 : return total average of array values

转载 作者:可可西里 更新时间:2023-11-01 09:48:20 28 4
gpt4 key购买 nike

我在 mongodb 中有这些数据

{ 
"name": "FooBar",
"__v": 0,
"user_rating": [
{
"date": "2017-06-02T16:19:32.002Z",
"user_rating": 5,
},
{
"date": "2017-06-02T16:19:46.803Z",
"user_rating": 3,
},
{
"date": "2017-06-02T16:20:01.244Z",
"user_rating": 5,
},
{
"date": "2017-06-02T16:15:54.673Z",
"user_rating": 3,
},
{
"date": "2017-06-02T16:53:42.489Z",
"user_rating": 5,
}
]
}

我需要对其进行过滤以显示商店名称、平均评分、评分总数以及 5 评分的数量、4 评分的数量等。

这是我期待的:

[
{
"_id":"FooBar",
"countRating":5,
"averageRating":4.2,
"ratings": [
{"num":3,"count":2},
{"num":5,"count":3}
]
}
]

但是,我似乎无法获得 averageRating - 相反,我获得了每个评级的两个总和的平均值。

这是我的 Mongo 查询:

 db.collection.aggregate([
{
$match: {"name": "FooBar"}
},
{
$unwind: "$user_rating"
},
{
$match: {"name": "FooBar"}
},
{
$group: {
_id: {
"name": "$name",
"rating": "$user_rating.user_rating"
},
averageRating: {$avg: "$user_rating.user_rating"},
countRating: {$sum: 1}
}
},
{
$group: {
_id: "$_id.name",
countRating: {"$sum": "$totalRatings"},
averageRating: {"$avg": "$averageRating"},
"rating": {
"$push": {
"num": "$_id.rating",
"count": "$totalRatings"
}
},
}
}]);

任何人都可以帮助获得这里的总体平均值吗?谢谢!!

最佳答案

db.collection.aggregate([
{ $match: {"name": "FooBar"} },
{ $unwind: "$user_rating" },
{
$group: {
_id : "$name",
avg: {$avg: "$user_rating.user_rating" },
ratings: {$push: "$user_rating.user_rating" }
}
},
{ $unwind: "$ratings" },
{
$group: {
_id: { name: "$_id", num: "$ratings", avg: "$avg" },
count: { $sum: 1 }
}
},
{
$group: {
_id: { name: "$_id.name", avg: "$_id.avg" },
ratings: { $push: { num: "$_id.num", count: "$count" }}
}
},
{ $project: {_id:0, name:"$_id.name", averageRating: "$_id.avg", ratings: 1}}
])

我在这里使用了额外的分组来计算总的平均评分。然后我展开结果并在分组键中传递计算的平均值。

输出:

{
"name" : "FooBar",
"averageRating" : 4.2,
"ratings" : [
{
"num" : 3,
"count" : 2
},
{
"num" : 5,
"count" : 3
}
]
}

关于arrays - 蒙戈聚合 : return total average of array values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371375/

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