[英]How to query MongoDB and group result by month using Pymongo?
我已經編寫了以下代碼,該代碼正確地按月份編號列出了我的地址集合並帶有計數,但這些是總數,因此我需要有效地添加一個條件,該條件只能返回“類型=綠色”的結果。 我無法解決如何僅在符合這些條件時進行計數。
result = db.address.aggregate([{"$group":{"_id": { "$month": "$date" },
"count":{"$sum":1} } } ])
list_of_months = ["nothing", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
result_sorted = sorted(result, key=lambda x: x['_id'], reverse=False)
for res in result_sorted:
print(list_of_months[res['_id']], ": ", res['count'])
使用$ match :
result = db.address.aggregate([{"$match": {"type": "green"}},
{"$group": {"_id": {"$month": "$date"},
"count": {"$sum": 1}}}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.