title: Aggregate and Count Items in a Result from MongoDB using pymongo & Flask
body: <p>I am trying to return a simple JSON result from MongoDB using pymongo in a Flask environment. Here's what I am doing:</p>
  
  <pre><code>def myResults():
      myCollection = db["my_data"]
      results = list(myCollection.find({},{"ID":1,"Response":1,"_id":0}))
      return jsonify(results=results)
  </code></pre>
  
  <p>When I do this, I get the following result. FYI <code>"ID"</code> is basically a made-up unique identifier.</p>
  
  <pre><code>{
    "result": [
      {
        "ID": 1, 
        "Response": "A"
      }, 
      {
        "ID": 4, 
        "Response": "B"
      }, 
      {
        "ID": 3, 
        "Response": "A"
      },
    ]
  } // and so on...
  </code></pre>
  
  <p><strong>I want to aggregate all the responses for a particular ID and show the count. Something that would look like this I guess (or if there's a better way):</strong></p>
  
  <pre><code>{
    "result": [
      {
        "ID": 1, 
        "A": 2,
        "B": 1,
        "C": 5,
        "Total": 8
      }, 
      {
        "ID": 4, 
        "A": 0,
        "B": 5,
        "C": 18,
        "Total": 23
      }, 
      {
        "ID": 3, 
        "A": 12,
        "B": 6,
        "C": 8,
        "Total": 26
      },
    ]
  }
  </code></pre>
  
  <p>Someone on StackOverflow recommend using <code>aggregate()</code>. But it's not really working for me.</p>
  
  <pre><code>allResults = surveyCollection.aggregate([
      {"$unwind": result }, 
      {"$group": {"_id": result.ID, "A": {"$sum": 1}, "B": {"$sum": 1}}},
      {"$group": {"_id": None, "result": {"$push": {"ID": "$ID", "A": "$A", "B": "$B"}}}}
  ])
  
  return jsonify(allResults)
  </code></pre>
  
  <p>I get an error: <code>AttributeError: 'list' object has no attribute 'ID'</code>.</p>
  
  <p>Is there no simpler method by using just <code>find()</code> or <code>count()</code>?</p>