简体   繁体   English

如何使用Pymongo查询MongoDB并按月分组结果?

[英]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 : 使用$ match

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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