我想计算从MongoDB中提取的以下JSON结果中与每个ID关联的每种响应类型的总数:
{
"test": [
{
"ID": 4,
"response": "A"
},
{
"ID": 4,
"response": "B"
},
{
"ID": 1,
"response": "A"
},
{
"ID": 3,
"response": "B"
},
{
"ID": 2,
"response": "C"
}
]
}
// and so on...
例如,我想将JSON构造成这样的东西:
{
"test": [
{
"ID": 4,
"A": 1,
"B": 1
},
{
"ID": 3,
"B": 1
},
{
"ID": 2,
"C": 1
},
{
"ID": 1,
"A": 1
}
]
}
我的查询看起来像这样,因为我只是测试并尝试仅针对ID 4进行计数响应。
surveyCollection.find({"ID":4},{"ID":1,"response":1,"_id":0}).count():
但是我收到以下错误:TypeError: 'int' object is not iterable
答案 0 :(得分:1)
您需要的是使用"aggregation framework"
surveyCollection.aggregate([
{"$unwind": "$test" },
{"$group": {"_id": "$test.ID", "A": {"$sum": 1}, "B": {"$sum": 1}}},
{"$group": {"_id": None, "test": {"$push": {"ID": "$ID", "A": "$A", "B": "$B"}}}}
])
从pymongo 3.x开始,aggregate()
方法在结果集上返回CommandCursor
,因此您可能需要先将其转换为列表。
In [16]: test
Out[16]: <pymongo.command_cursor.CommandCursor at 0x7fe999fcc630>
In [17]: list(test)
Out[17]:
[{'_id': None,
'test': [{'A': 1, 'B': 1},
{'A': 1, 'B': 1},
{'A': 1, 'B': 1},
{'A': 2, 'B': 2}]}]
使用return list(test)
代替