所以我的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
仅返回评论总数。我想获得评论和回复的总数
答案 0 :(得分: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"])
答案 1 :(得分:0)
使用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,而我们只是将所需的属性投影到下一阶段,而且我们还在寻找comment数组的大小。注释数组的大小存储在临时属性comments_size
第二部分使用$ unwind破坏comments
和comments.replies
中的嵌套数组,展开comments
数组,保持comments.replies
数组不变
第三部分使用$ project查找答复的大小,并将其存储在临时属性replies_size
第四部分和最后一部分再次使用$ project和$ sum为comments_size
和replies_size
的