2014-10-20 13 views
7

ich eine Reihe von Einträgen in der goals Sammlung haben, die wie folgt aussieht:MongoDB Aggregat/Gruppe/Summe Abfrage Abfrage pymongo übersetzt

{"user": "adam", "position": "attacker", "goals": 8} 
{"user": "bart", "position": "midfielder", "goals": 3} 
{"user": "cedric", "position": "goalkeeper", "goals": 1} 

Ich möchte eine Summe aller Ziele berechnen. In MongoDB Shell mache ich es wie folgt aus:

> db.goals.aggregate([{$group: {_id: null, total: {$sum: "$goals"}}}]) 
{ "_id" : null, "total" : 12 } 

Jetzt möchte ich das gleiche in Python mit pymongo zu tun. Ich habe versucht, sowohl db.goals.aggregate() und db.goals.group(), aber bisher keinen Erfolg.

Nichtarbeits Anfragen:

> 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 

Irgendwelche Ideen, wie dies zu tun?

Antwort

11

Verwenden Sie einfach ein Rohr mit Aggregat.

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