Ahmed Rhuma
Ahmed Rhuma

Reputation: 71

MongoDB group by non standard $week custom start day of week

I'm building a dynamic software that gives the ability to set custom start day of week depending on the business needs. Therefore we have start_day_of_week a number represents the day.

Now on grouping by mongodb the $week property will consider the week starts on Monday.

But I want to make it start based on the value of start_day_of_week it might be Saturday, Sunday any day of the week.

I can't even think about an idea to do this, can you enlighten me please?

Thanks.

Upvotes: 0

Views: 352

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59513

The documentation is quite clear:

Returns the week of the year for a date as a number between 0 and 53.

Weeks begin on Sundays, and week 1 begins with the first Sunday of the year. Days preceding the first Sunday of the year are in week 0. This behavior is the same as the “%U” operator to the strftime standard library function.

You may check $isoWeek

If you like to group by other days, then you can work with offset, e.g.

{ $isoWeek: { date: { $add: [ "$date", 3*24*60*60000 ] } } } 

to group on weeks starting by Thursday.

Upvotes: 2

Related Questions