Search code examples
javascriptreactjsmongodbmongodb-query

How do you get a date to correspond to the week number of a year


I'm pretty new to javascript, and I'm working on creating a Dashboard. I want to get the number of orders per a week, which I have been able to do. Right now, I get the number that corresponds to the week of the year, however, I would like to get the a date (Monday) that corresponds to that week. I have included what I have below. I would appreciate any help or guidance on how to do this. Thank you!

 const weeklyOrders = await Order.aggregate([
      {
        $group: {
          _id: { $dateToString: { format: '%U', date: '$createdAt' } },
          orders: { $sum: 1 },
        },
      },
      { $sort: { _id: 1 } },
    ]);

Edit:

 const weeklyOrders = await Order.aggregate([
      {

        $group: {
          _id:{ $dateFromParts: {
            isoWeekYear: {$year: '$createdAt' },
            isoWeek: { $isoWeek: '$createdAt' },
            isoDayOfWeek: 1
          },
        },
         
            orders: { $sum: 1 },
          },
        },
        { $sort: { _id: 1 } },
      ]);

Worked, but the date is in ISO date format. I tried to fix this in the code below, but that didn't work.

 const weeklyOrders = await Order.aggregate([
      {
        $group: {
          _id:{ date: {
            $dateToString: { format: '%m-%d-%Y' },
          },
          },
            orders: { $sum: 1 },
          },
        },
        { $sort: { _id: 1 } },

      {
        $addFields:{
          date: {
            $dateFromParts: {
              isoWeekYear: {$year: '$createdAt' },
              isoWeek: { $isoWeek: '$createdAt' },
              isoDayOfWeek: 1
          }
        }
      }
    },
      ]);

Solution

  • You can do following:

    1. use $year and $isoWeek to get the year and week number for the specific date
    2. use $dateFromParts with "isoDayOfWeek": 1 to convert back to Monday you want
    db.collection.aggregate([
      {
        "$addFields": {
          "monday": {
            $dateFromParts: {
              "isoWeekYear": {
                $year: "$createdAt"
              },
              "isoWeek": {
                $isoWeek: "$createdAt"
              },
              "isoDayOfWeek": 1
            }
          }
        }
      }
    ])
    

    Here is the Mongo playground for your reference.