Reputation: 3202
I've written the following code which correctly lists my address collection by month number with a count but these are the totals and I need to effectively add a condition which only returns results where "type = green". I can't work out how to only count when it matches these criteria.
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'])
Upvotes: 0
Views: 494
Reputation: 24007
Use $match:
result = db.address.aggregate([{"$match": {"type": "green"}},
{"$group": {"_id": {"$month": "$date"},
"count": {"$sum": 1}}}])
Upvotes: 1