【发布时间】:2020-02-28 06:03:55
【问题描述】:
我试图获得产品的平均评分,加上每个评分的计数,并返回实际评分,并使用分页来限制返回的数量,而不影响平均或计数。
所以我正在尝试实现这样的目标:
这是我的评分集:
{
"productId": "3"
"userid" : 5,
"rating" : 5
"comment": "this is nice"
},
{
"productId": "3"
"userid" : 2,
"rating" :4
"comment": "this is very nice"
}
这就是我想要的结果
{
"_id" : 1,
"avgRating": "3.6"
"counts" : [
{
"rating" : 5,
"count" : 8
},
{
"rating" : 3,
"count" : 2
},
{
"rating" : 4,
"count" : 4
},
{
"rating" : 1,
"count" : 4
}
],
"ratings": [
{
"productId": "3"
"userid" : 5,
"rating" : 5
"comment": "this is nice"
},
{
"productId": "3"
"userid" : 2,
"rating" :4
"comment": "this is very nice"
},
{
"productId": "3"
"userid" : 12,
"rating" : 4
"comment": "this is okay"
}
]
}
到目前为止,我有这个给我每个评分的计数:
db.votes.aggregate([
{ $match: { postId: {$in: [1,2]} } },
{
$group: { _id: { post: "$postId", rating: "$vote" }, count: { $sum: 1 } }
},
{
$group: {
_id: "$_id.post",
counts: { $push: { rating: "$_id.rating", count: "$count" } }
}
}
])
【问题讨论】:
-
原始数据是什么样的?它是如何存储在 Mongo 中的。如果不知道你的 Mongo“模式”是什么样的,几乎不可能提供帮助。
-
更新添加架构@MattOestreich