这是一些示例文档(我只显示用过的文件,文档中还有其他字段):
{"id":1111,"info":{"score":90,"class":"algorithm","room":101}}
{"id":1112,"info":{"score":60,"class":"java","room":401}}
{"id":1113,"info":{"score":100,"class":"python","room":301}}
根据https://docs.mongodb.com/manual/reference/operator/aggregation/bucket/index.html,我想做的是计算分数分布,我使用存储桶操作。
pipeline = {
{"$match": {"_id": ObjectId(_id)}},
{"$bucket": {
"groupBy": "$info.score",
"boundaries": [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100],
"output": {
"count": {"$sum": 1}
}
}}
}
score_distribution = list(Students.objects.aggregate(*pipeline))
但是,我遇到了错误:
"count": {"$sum": 1}
TypeError: unhashable type: 'dict'
我找不到类型错误的原因,有人可以提出建议吗?
答案 0 :(得分:1)
对不起,我犯了一个超级编辑错误。 管道应为数组,而不是字典。
pipeline = [
{"$match": {"_id": ObjectId(_id)}},
{"$bucket": {
"groupBy": "$info.score",
"boundaries": [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100],
"output": {
"count": {"$sum": 1}
}
}}
]