[英]How to find and count in MongoDB for specific items?
我想在从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
您需要的是使用“聚合框架”
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开始,gregation 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)
代替
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.