Mongo为所有文档聚合字典列表中的值总和

2024-09-30 00:32:34 发布

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

我收集了如下“评论”:

{
comment_id:10001
aspects:[
 {
   name:'aspectA',
   positive:2
   negative:3
   neutral:1
  },
 {
   name:'aspectB',
   positive:1
   negative:5
   neutral:3
  }
},
{
comment_id:10002
aspects:
 {
   name:'aspectA',
   positive:2
   negative:1
   neutral:2
  },
 {
   name:'aspectB',
   positive:3
   negative:4
   neutral:1
  }
}
]

注释中的文档数大于100K。我必须找到所有方面的正、负和中性计数,即所有文档的aspects字段(如上所述的DICT列表)中每个方面的正、负和中性之和。我发现mapreduce可以用来完成这项任务,但我找不到足够的文档来构建查询

有没有一种方法可以通过一个查询找到它


Tags: name文档id列表comment评论dict计数
1条回答
网友
1楼 · 发布于 2024-09-30 00:32:34

要按aspects.name求和,可以使用以下聚合:

db.comments.aggregate([{
    $unwind: "$aspects"
}, {
    $group: {
        _id: "$aspects.name",
        "positive": { $sum: "$aspects.positive" },
        "negative": { $sum: "$aspects.negative" },
        "neutral": { $sum: "$aspects.neutral" }
    }
}])

pymongo一起:

from pymongo import MongoClient
import pprint

client = MongoClient('localhost', 27017)

db = client.testDB

pipeline = [
    {"$unwind": "$aspects"},
    {"$group": {
        "_id": "$aspects.name", 
        "positive": { "$sum": "$aspects.positive" }, 
        "negative": { "$sum": "$aspects.negative" }, 
        "neutral": { "$sum": "$aspects.neutral" }
        }
    }
]

pprint.pprint(list(db.comments.aggregate(pipeline)))

相关问题 更多 >

    热门问题