本文介绍了MongoDB 聚合/组/总和查询转换为 pymongo 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 goals 集合中有一组条目,如下所示:

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}

我想计算所有目标的总和.在 MongoDB shell 中,我这样做:

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 }

现在我想使用 pymongo 在 Python 中做同样的事情.我尝试同时使用 db.goals.aggregate()db.goals.group(),但到目前为止没有成功.

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.

非工作查询:

> 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?

推荐答案

只需将管道聚合结合使用.

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

这篇关于MongoDB 聚合/组/总和查询转换为 pymongo 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 02:54