Group items by date, in order to easily provide a report

I am using Express and mongoose as back-end, my application works with travels and in one of front-end page’s, specifically the ‘/reports’ page, requires back-end to send and group travels by day, in case user specify year and month and by month in case of user just insert an year, and by year in case user doesn’t specify anything. How can I easily return:

months: { January: [] , February: [] } , in case of a year period.
days: { 1: [] , 2: [] } , in case of a year and month period
years: { 2020: [] , 2021: [] } , in case nothing was informed

Hi @Marcello_Manuel_Borg,

Find the following agrgegation pipeline, suit it to your own needs -

[
    {
        $match: {
            // your matching statements
        }
    },
    {
        $bucket: {
            boundaries: boundary_var,
            groupBy: grouping_var
        }
    }
]

You can define the variables - boundary_var and grouping_var based on your conditions coming in request. Ex -
In case of year period -

grouping_var = '$monthKey'
buckets = [1,2,3,4,5,6,7,8,9,10,11,12]

And similar for your other use cases. You might want to add some project keys for month names, converting your date key in the document to get Month value, etc.
Checkout - $bucket, $project, $month, $year

Ok, shrey. I will try it. If it solves my problem, i will mark you comment as solution. thanks, man!

1 Like