作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 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/
我是一名优秀的程序员,十分优秀!