Search code examples
sqlmongodbshellmongo-shell

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


i want a equivalent query to

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

If you clearly go into the SQL query i want total _id counts for month=1 and group by year

The output would get for this is

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

Tried equivalent query to get in Mongo

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

But using the above mongo query am getting total for all 12 months, i just want for month 1, how to filter this in $match for month 1. Where displayDate is the field for date.


Solution

  • You want to use $month

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