Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregate/group/sum query translated to pymongo query

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?

like image 982
MR22 Avatar asked Oct 20 '14 12:10

MR22


People also ask

Can we use $and in aggregate MongoDB?

You can use $and with aggregation but you don't have to write it, and is implicit using different filters, in fact you can pipe those filters in case one of them needs a different solution.

How do you sum the value of a key across all documents in a MongoDB collection?

To get sum the value of a key across all documents in a MongoDB collection, you can use aggregate().

How do I sum fields in MongoDB?

If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values. If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all operands are non-numeric, $sum returns 0 .

How does MongoDB calculate sum of salary?

Step 2.1 - We will group employee by firstName and find sum of salary of each group. Step 2.2- We will use aggregate() method, $sum operator and $group operator. Step 4.3 - Then we will group employee by firstName and find sum of salary of each group.


1 Answers

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}]}
like image 165
Anzel Avatar answered Oct 10 '22 16:10

Anzel