问题
I have a set of entries 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 a sum of all goals. In 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 no success so far.
Non working queries:
> 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?
回答1:
Just use a 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}]}
来源:https://stackoverflow.com/questions/26465846/mongodb-aggregate-group-sum-query-translated-to-pymongo-query