我有一组条目goals
集合看起来像这样:
{"user": "adam", "position": "attacker", "goals": 8}
{"user": "bart", "position": "midfielder", "goals": 3}
{"user": "cedric", "position": "goalkeeper", "goals": 1}
我想计算所有目标的总和。在 MongoDB shell 中我这样做:
> db.goals.aggregate([{$group: {_id: null, total: {$sum: "$goals"}}}])
{ "_id" : null, "total" : 12 }
现在我想使用 pymongo 在 Python 中做同样的事情。我尝试同时使用db.goals.aggregate()
and db.goals.group()
,但到目前为止还没有成功。
非工作查询:
> 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
有什么想法如何做到这一点?