skip to Main Content

I want to group all the data with startDate>=today-3 or <=today+3. Here is the database:

 "startDate": {
"$date": "2024-03-05T00:00:00Z" }

Here is the query:

const dailyPlans = await DailyPlan.aggregate([
  {
    $match: {
      _id: { $in: allPlansID },
      startDate: {
        $gte: startUtcDate,
        $lte: endUtcDate,
      },
    },
  },
  {
    $group: {
      _id: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: {
            $toDate: "$startDate",
          },
        },
      },
      count: { $sum: 1 },
    },
  },
]);

2

Answers


  1. This is how your $group stage should look like:
    (here is the correct syntaxt)

        $group: {
          _id: {
            $dateToString: {
              format: "%Y-%m-%d",
              date: "$startDate",
            },
          },
          count: { $sum: 1 },
        },
    

    In your aggregate query, you’re using $toDate to convert the startDate field to a date object. However, it seems unnecessary because startDate is already stored as a date object I assume based on your DailyPlan.find(query) in the comments

    Login or Signup to reply.
  2. Your criteria looks like a $and criteria to me. You can leave all the date processing to $dateAdd/$dateSubtract. $dateTrunc can be used to make $$NOW, which refers to current datetime, to date only.

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $and: [
              {
                $gte: [
                  "$startDate",
                  {
                    "$dateSubtract": {
                      "startDate": {
                        $dateTrunc: {
                          date: "$$NOW",
                          unit: "day"
                        }
                      },
                      "unit": "day",
                      "amount": 3
                    }
                  }
                ]
              },
              {
                $lte: [
                  "$startDate",
                  {
                    "$dateAdd": {
                      "startDate": {
                        $dateTrunc: {
                          date: "$$NOW",
                          unit: "day"
                        }
                      },
                      "unit": "day",
                      "amount": 3
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search