MongoDB aggregate / group / sum request translated to pymongo request

I have a recordset in the goals collection that looks like this:

 {"user": "adam", "position": "attacker", "goals": 8} {"user": "bart", "position": "midfielder", "goals": 3} {"user": "cedric", "position": "goalkeeper", "goals": 1} 

I want to calculate the sum of all goals. In the MongoDB shell, I do it like this:

 > db.goals.aggregate([{$group: {_id: null, total: {$sum: "$goals"}}}]) { "_id" : null, "total" : 12 } 

Now I want to do the same in Python using pymongo. I tried using both db.goals.aggregate() and db.goals.group() , but so far have not achieved anything.

Broken requests:

 > query = db.goals.aggregate([{"$group": {"_id": None, "total": {"$sum": "$goals"}}}]) {u'ok': 1.0, u'result': []} > db.goals.group(key=None, condition={}, initial={"sum": "goals"}, reduce="") SyntaxError: Unexpected end of input at $group reduce setup 

Any ideas how to do this?

+7
python mongodb pymongo
source share
1 answer

Just use pipe with aggregate .

 pipe = [{'$group': {'_id': None, 'total': {'$sum': '$goals'}}}] db.goals.aggregate(pipeline=pipe) Out[8]: {u'ok': 1.0, u'result': [{u'_id': None, u'total': 12.0}]} 
+11
source share

All Articles