我有两个收藏,名字是post and comment。
模型结构如下。
我想使用聚合查询帖子并按评论(如长度总和)排序,目前我可以在以下查询语句中查询帖子评论(如长度总和)。
我的问题是如何查询帖子并加入评论集合蒙戈版本2.6。我知道Mongo 3.2之后有查找功能。
我想查询帖子集合并按国外评论喜欢的长度排序。在 mongo 2.6 中有最好的方法吗?
post
{
"_id": ObjectId("5a39e22c27308912334b4567"),
"uid": "0",
"content": "what is hello world mean?",
}
comment
/* 1 */
{
"_id": ObjectId("5a595d8c2703892c3d8b4567"),
"uid": "1",
"post_id": "5a39e22c27308912334b4567",
"comment": "hello world",
"like": [
"2"
]
}
/* 2 */
{
"_id": ObjectId("5a595d8c2703892c3d8b4512"),
"uid": "2",
"post_id": "5a39e22c27308912334b4567",
"comment": "hello stackoverflow",
"like": [
"1",
"2"
]
}
查询帖子评论如 sum
db.getCollection('comment').aggregate([
{
"$match": {
post_id: "5a39e22c27308912334b4567"
}
},
{
"$project": {
"likeLength": {
"$size": "$like"
},
"post_id": "$post_id"
}
},
{
"$group": {
_id: "$post_id",
"likeLengthSum": {
"$sum": "$likeLength"
}
}
}
])