MongoDB聚合/组/总和查询转换为pymongo查询

时间:2014-10-20 12:33:36

标签: python mongodb pymongo

我在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 }

现在我想在Python中使用pymongo做同样的事情。我尝试使用db.goals.aggregate()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

任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:11)

只需使用管道 聚合

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}]}