简体   繁体   中英

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

Use $match :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM