1

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

2
  • It is generally not a good idea to edit your post with given answer Commented Aug 13, 2015 at 21:30
  • Sorry about that. Thanks for the edit. Commented Aug 13, 2015 at 21:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.