I would like to count the total number of each type of responses associated with each ID in the following JSON result that I am extracting from MongoDB:
{
"test": [
{
"ID": 4,
"response": "A"
},
{
"ID": 4,
"response": "B"
},
{
"ID": 1,
"response": "A"
},
{
"ID": 3,
"response": "B"
},
{
"ID": 2,
"response": "C"
}
]
}
// and so on...
So for example, I would like to structure the JSON into something like this:
{
"test": [
{
"ID": 4,
"A": 1,
"B": 1
},
{
"ID": 3,
"B": 1
},
{
"ID": 2,
"C": 1
},
{
"ID": 1,
"A": 1
}
]
}
My query looks something like this because I was just testing and trying to tally responses just for ID 4.
surveyCollection.find({"ID":4},{"ID":1,"response":1,"_id":0}).count():
But I get the following error: TypeError: 'int' object is not iterable
What you need is use the "aggregation framework"
From pymongo 3.x the
aggregate()method returns aCommandCursorover the result set so you may need to convert it first into list.Use
return list(test)instead