如何使用 MongoDB 中的 $match 按年份获取特定月份和组的计数

How to get count for specfic month and group by year with $match in MongoDB

我想要一个与

等效的查询
    SELECT YEAR(displayDate) AS YEAR, 
           count(_id) as Total
    from collection
    where Month(displayDate)=1 
    group by  YEAR(displayDate);

如果您清楚地进入 SQL 查询,我希望总计 _id 计数 month=1 并按 year

分组

为此得到的输出是

-----------------------
Year   |  Total
-----------------------
2016   | 30
2017   | 45
2018   | 60
-----------------------

尝试了等效查询以进入 Mongo

db.collection.aggregate(
{$match: {}},
{$group : {
_id : {$year : "$displayDate"},
count : {$sum : 1}
}})

但是使用上面的 mongo 查询得到所有 12 个月的总数,我只想要第 1 个月,如何在 $match 中为第 1 个月过滤这个。displayDate是日期字段。

您想使用$month

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $eq: [{$month: "$displayDate"}, 1]
            }
        }
    },
    {
        $group: {
            _id: {$year: "$displayDate"},
            count: {$sum: 1}
        }
    }
])