Search code examples
mongodbmongodb-queryaggregation-frameworkaggregationnosql-aggregation

how to add 7 days in date manually using mongodb(aggregation)?


I have a query in which I'm getting data using start Date and end Date. And it's working perfectly fine. now I want to add 7 days in my start date using aggregation and want to get data of start Date + 7 added days. i have tried the below code but couldn't get any success


  {
    $match: {
      publishedAt: {
        $lt: new Date(startDate),
        $gte: new Date(endDate),
      },
    },
  },
  {
    $set: {
      publishedAt: {
        $add: [new Date(startDate), 1000 * 60 * 60 * 24],
      },
    },
  },


Solution

  • Use this:

       {
          $set: {
             publishedAt: {
                $dateAdd: {
                   startDate: new Date(startDate),
                   unit: "day",
                   amount: 7
                }
             }
          }
       }
    

    Or use a 3rd party library, e.g. Luxon

       {
          $set: {
             publishedAt: DateTime.now().plus({ days: 7 }).toJSDate()
          }
       }