Mongo 所有文档的字典列表中值的总和
Mongo Aggregate Sum of values in a list of dictionaries for all documents
我有一个合集'comments'如下:
{
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
字段(如上所述,这是一个字典列表)中每个方面的正面、负面和中性的总和。我发现 mapreduce 可以用来完成任务,但我找不到足够的文档来构建查询。
有没有一种方法可以使用一次查询找到它?
要按 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)))
我有一个合集'comments'如下:
{
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
字段(如上所述,这是一个字典列表)中每个方面的正面、负面和中性的总和。我发现 mapreduce 可以用来完成任务,但我找不到足够的文档来构建查询。
有没有一种方法可以使用一次查询找到它?
要按 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)))