Reputation: 1763
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
Upvotes: 1
Views: 222
Reputation: 61225
What you need is use the "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"}}}}
])
From pymongo 3.x the aggregate()
method returns a CommandCursor
over the result set so you may need to convert it first into list.
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}]}]
Use return list(test)
instead
Upvotes: 1