MongoDB如何获得评论+回复的数量

2024-04-18 11:07:00 发布

您现在位置:Python中文网/ 问答频道 /正文

所以在我的MongoDB实例中有这个结构

{
  "post_body": "test",
  "author": "test1",
  "comments":[
    {
      "comment_body": "comment test",
      "comment_author": "test2",
      "replies": [
        {
          "reply_body": "reply test1",
          "reply_author": "test3"
        },
        {
          "reply_body": "reply test2",
          "reply_author": "test2"
        }
      ]
    }
  ]
}

我想得到评论+回复的总数

所以我想要的输出应该是

{
    "post_body": "test"
    "author": "test1",
    "comment_count": 3
}

到目前为止,使用$project只返回注释总数。我想得到评论+回复的总数


Tags: 实例testmongodbcomment评论bodyreplypost
2条回答

使用Aggregation Pipeline我们可以得到期望的结果

下面的查询使用管道阶段$project$unwind和管道操作符$size$sum

db.collection_name.aggregate([
  { $project: {
     "post_body": 1, 
     "author": 1,
     "comments":1,
     "comments_size":{$size: "$comments" }
    }
  }, 
  { $unwind: "$comments" }, 
  { $project: {
     "post_body": 1, 
     "author": 1,
     "comments":1,
     "comments_size":1, 
     "replies_size" : {$size: "$comments.replies"} 
    }
  },
  { $project: {
     "_id":0, 
     "post_body": 1,
     "author": 1,
     "comments_count":{$sum:["$comments_size", "$replies_size"]}
    }
  }
])

聚合查询的第一部分使用$project,我们只是将所需的属性投影到下一个阶段,还将查找注释数组的大小。注释数组的大小存储在临时属性comments_size

第二部分使用$unwind来断开commentscomments.replies中的嵌套数组,comments数组被解除,而comments.replies数组保持不变

第三部分使用$project查找回复的大小,并将其存储在临时属性replies_size

第四部分也是最后一部分再次使用$project和comments_sizereplies_size的$sum来获得所需的结果

import pymongo
from bson.objectid import ObjectId
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
db = myclient["test"]
comments_col = db["comments"]
doc = {
    "post_body": "test",
    "author": "test1",
    "comments": [
        {
            "comment_body": "comment test",
            "comment_author": "test2",
            "replies": [
                {
                    "reply_body": "reply test1",
                    "reply_author": "test3"
                },
                {
                    "reply_body": "reply test2",
                    "reply_author": "test2"
                },
            ]
        }
    ]
}

def insert(doc1):
    id_comment = comments_col.insert(doc1)
    return id_comment
def find(id_comment):
    comment = comments_col.find_one({"_id": ObjectId(str(id_comment))})
    return comment
if __name__ == "__main__":
    id_comment = insert(doc)
    comment = find(id_comment)
    print("comments with replies : ", comment["comments"])
    print("\n")
    print("replies : ", comment["comments"][0]["replies"])
    print("\n")
    print("comment_author : ", comment["comments"][0]["comment_author"])
    print("\n")
    print("comment_body : ", comment["comments"][0]["comment_body"])

相关问题 更多 >