按月聚合组并按给定年份匹配

Aggregate group by months and match by given year

我正在尝试按给定年份(比方说 2008 年)进行匹配,然后从那里按月分组,以便找到 2008 年每个月的计数。到目前为止,我可以按月分组,但是我无法仅按特定年份进行过滤。 date 列存储为日期时间对象

database.coll.aggregate([
        
        # some expression that will only select year e.g. 2018
        {$match : {}},
    
     {$group : {
         _"id" : {$month : $date},   # group by year
         "total" : {$sum : 1}          # count values in each group
     },

    }])

{$match: {$expr: {$eq: [2008, {$year: "$date"}] } } }

$expr 允许您在 $match

中使用任何有效的聚合表达式