Home > Blockchain >  MongoDB: Aggregate query is not passing value inside the function
MongoDB: Aggregate query is not passing value inside the function

Time:02-26

I am facing a problem with the Mongoose aggregation query. I have the following schema which is an array of objects and contains the endDate value.

[
  {
    "id": 1,
    "endDate": "2022-02-28T19:00:00.000Z"
  },
  {
    "id": 2,
    "endDate": "2022-02-24T19:00:00.000Z"
  },
  {
    "id": 3,
    "endDate": "2022-02-25T19:00:00.000Z"
  }
]

So, during the aggregation result, I have to add a new field name isPast, It contains the boolean value, and perform the calculation to check if the endDate is passed or not. If it is already passed, then isPast will be true otherwise false.

I am using the isBefore function from the moment library which returns the boolean. But inside this function facing a problem regarding passing the endDate value. $endDate is passing as a string, not a value.

Is there a way to pass the value of endDate inside the function?

const todayDate = moment(new Date()).format("YYYY-MM-DD");

db.collection.aggregate([
  {
    $addFields: {
      "isPast": moment('$endDate', 'YYYY-MM-DD').isBefore(todayDate)
    },

  },

])

CodePudding user response:

You can achieve without momentjs. Use $toDate to convert date-time string to date

db.collection.aggregate([
  {
    $addFields: {
      "isPast": {
        $gt: [
          new Date(),
          {
            $toDate: "$endDate"
          }
        ]
      }
    }
  }
])

Sample Mongo Playground


If you just want to compare for date only:

db.collection.aggregate([
  {
    $set: {
      "currentDate": "$$NOW",
      "endDate": {
        $toDate: "$endDate"
      }
    }
  },
  {
    $addFields: {
      "isPast": {
        $gt: [
          {
            "$dateFromParts": {
              "year": {
                $year: "$currentDate"
              },
              "month": {
                $month: "$currentDate"
              },
              "day": {
                "$dayOfMonth": "$currentDate"
              }
            }
          },
          {
            "$dateFromParts": {
              "year": {
                $year: "$endDate"
              },
              "month": {
                $month: "$endDate"
              },
              "day": {
                "$dayOfMonth": "$endDate"
              }
            }
          }
        ]
      }
    }
  }
])

Sample Mongo Playground (Compare date only)

  • Related