簡體   English   中英

MongoDB聚合/組/總和查詢轉換為pymongo查詢

[英]MongoDB aggregate/group/sum query translated to pymongo query

我在goals集合中有一組條目,如下所示:

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

我想計算所有目標的總和。 在MongoDB shell中我這樣做:

> 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

任何想法如何做到這一點?

只需使用帶聚合管道

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM