【发布时间】:2017-12-25 12:13:30
【问题描述】:
我有两个收藏,分别是post和comment。 模型结构如下。 我想使用聚合查询帖子并按长度和之类的 cmets 排序,目前我可以在以下查询语句中查询长度和之类的帖子 cmets。
我的问题是如何在 Mongo 版本 2.6 中查询帖子和加入评论集合。我知道 Mongo 3.2 之后有一个查找功能。
我想查询帖子集合并按外国cmets喜欢的长度排序。在mongo 2.6中有最好的方法吗?
发布
{
"_id": ObjectId("5a39e22c27308912334b4567"),
"uid": "0",
"content": "what is hello world mean?",
}
评论
/* 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之类的post cmets
db.getCollection('comment').aggregate([
{
"$match": {
post_id: "5a39e22c27308912334b4567"
}
},
{
"$project": {
"likeLength": {
"$size": "$like"
},
"post_id": "$post_id"
}
},
{
"$group": {
_id: "$post_id",
"likeLengthSum": {
"$sum": "$likeLength"
}
}
}
])
【问题讨论】:
标签: mongodb aggregation-framework