MongoDB聚合/分组/求和查询转换为pymongo查询
我有一组在 goals
这个集合里的数据,长这样:
{"user": "adam", "position": "attacker", "goals": 8}
{"user": "bart", "position": "midfielder", "goals": 3}
{"user": "cedric", "position": "goalkeeper", "goals": 1}
我想要计算所有目标的总和。在 MongoDB 的命令行里,我是这样做的:
> 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 个回答
14
只需要用一个管道配合聚合就可以了。
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}]}