MongoDB aggregate/group/sum query translated to pymongo query

不想你离开。 提交于 2019-12-30 04:44:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!