我已经编写了以下代码,这些代码正确地按月份编号列出了我的地址集合,但这些是总数,我需要有效地添加一个条件,只返回结果,其中" type = green&# 34 ;.我无法确定如何只在符合这些标准时进行计数。
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'])
答案 0 :(得分:1)
使用$match:
result = db.address.aggregate([{"$match": {"type": "green"}},
{"$group": {"_id": {"$month": "$date"},
"count": {"$sum": 1}}}])