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?
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.
To get sum the value of a key across all documents in a MongoDB collection, you can use aggregate().
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 .
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.
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}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With