1

所以我在我的 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仅返回评论总数。我想得到评论+回复的总数

4

2 回答 2

1
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"])
于 2020-03-11T10:14:38.217 回答
0

使用聚合管道我们可以得到想要的结果

下面的查询使用管道阶段$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 打破 and 中的嵌套数组commentscomments.replies数组comments展开并且comments.replies数组保持不变

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

第四部分和最后一部分再次使用 $project 和 $sumcomments_sizereplies_size获得所需的结果

于 2020-03-11T13:39:43.353 回答