Johnny John Boy
Johnny John Boy

Reputation: 3202

How to query MongoDB and group result by month using Pymongo?

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

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

Use $match:

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

Upvotes: 1

Related Questions