我需要运行两次分组查询来找到评论中平均点赞最高的帖子。以下是我的查询的初始阶段。
db.posts.aggregate([
{"$unwind": "$comments"},
{"$match":
{
"$comments.type": {
"$ne" : "spam"
},
}
}
])
运行上述查询后,我看到的内容如下所示。
{
"_id" : ObjectId("50b59cd75bed76f46522c465"),
"comment_id" : 49,
"post_id" : 29,
"likes" : {
"type" : "accepted",
"like" : 3
}
},
{
"_id" : ObjectId("50b59cd75bed76f46522c465"),
"comment_id" : 49,
"post_id" : 29,
"likes" : {
"type" : "rejected",
"like" : 7
}
}
现在我想要做的是,首先找到这些有效记录中特定评论获得的平均点赞数,然后在每篇帖子中,将每条评论的平均点赞数相加,再除以每篇帖子总共的评论数,以此求得每个帖子的平均点赞数。
请注意,comment_id 仅在同一 post_id 中才是唯一的。换句话说,存在 post_id 为28,comment_id 为49 的记录。
我尝试了以下查询。
db.posts.aggregate([
{"$unwind": "$comments"},
{"$match":
{
"$comments.type": {
"$ne" : "spam"
},
}
},
{"$group" :
{
"_id": "$_id",
"comment_avg":
{
"$avg":"$comments.like"
}
}
}])
我得到以下内容:
{
"_id" : ObjectId("50b59cd75bed76f46522c44d"),
"comment_avg" : 61.074253191058865
},
{
"_id" : ObjectId("50b59cd75bed76f46522c34e"),
"comment_avg" : 46.82622896256565
}
如您所见,我已经丢失了post_id信息。我尝试使用$project,但我认为我做错了。