我想在mongodb中按特定字段加总upvotes的数量。 例如,返回作者约翰所获得的赞助人数的总和。
{
"_id": "fc0996a9726e4bf08c3d614afe05c7a8",
"blog_id": "f8da5ae532aa44f6a54d86fd822f7d52",
"author": "John",
"content": "Hello",
"upvotes": 3,
}
{
"_id": "dea0a9713a734717920b652eed268b99",
"blog_id": "f8da5ae532aa44f6a54d86fd822f7d52",
"author": "John",
"content": "Hello",
"upvotes": 2,
}
{
"_id": "3d286c4ce54046f4aac9ea627a48f04e",
"blog_id": "f8da5ae532aa44f6a54d86fd822f7d52",
"author": "John",
"content": "Hello",
"upvotes": 1,
}
{
"_id": "6782b555dd8c47f58dba28e60fda4a5f",
"blog_id": "f8da5ae532aa44f6a54d86fd822f7d52",
"author": "123",
"content": "Bye",
"upvotes": 2,
}
我如何总结upvotes并返回值6,只有John得到的upvotes。 另外,我正在使用python作为web应用程序,带烧瓶。
谢谢
答案 0 :(得分:0)
您可以使用$group
聚合框架:
db.collection.aggregate([{ $group: { _id: { author:'$author'}, totalUpvotes: { $sum: "$upvotes" }}}])