2017-07-19 94 views
0

我已經寫了下面的代碼,它正確地列出了我的地址集合的月份數與計數,但這些是總數,我需要有效地添加條件,只返回結果「type = green」。我無法計算出只有當它符合這些標準時纔算數。如何使用Pymongo按月查詢MongoDB和組結果?

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']) 

回答

1

使用$match

result = db.address.aggregate([{"$match": {"type": "green"}}, 
           {"$group": {"_id": {"$month": "$date"}, 
              "count": {"$sum": 1}}}]) 
+0

嗨 - 我只是嘗試這樣做,它失敗了。我認爲你在類型和綠色之間做了一個拼寫錯誤,而不是冒號。你能否更新,我會標記爲正確的?感謝您的幫助。 –

+0

謝謝,更新! –