Search code examples
mongodbgroupingdayofweek

$week function and first day of week in aggregation


I use $project operator to extract week part from Date, then do grouping by weeks in aggregation pipeline:

{ $project: { 
    year: { $year: [ "$datetime" ] }, 
    week: { $week: [ "$datetime" ] }, 
    ....
    }
},
....
{ $group: { 
    _id: { 
        year: "$year", 
        week: "$week", 
        },
        .....
    }
}

But the $week operator I use, always counts Sunday as a first day of week, and we use Monday as first day of week in our location. Therefore, the results grouped by week are always incorrect for me.

The existing request in mongo tracking system seems to be unresolved for more than a year (is it really so rarely needed option?).

Any possible options are welcome. Maybe there is possibility to create some custom function in javascript and add/replace it somewhere?


Solution

  • MongoDB has finally added $isoWeek and $isoWeekYear in 3.4 which will start the week on a Monday.

    More information: https://docs.mongodb.com/manual/reference/operator/aggregation/isoWeek/