Home > Mobile >  How to convert string to ISODate in mongodb and compare it with $$NOW
How to convert string to ISODate in mongodb and compare it with $$NOW

Time:06-30

Here, In my mongo collection, the date type column data is stored as string. I have a view where I need to compare this date with current date and time $$NOW. Since my date is stored as string. The query is getting executed but not getting compared. I tried to convert this string to date type but the data changed like this 2022-05-23 1:28:36 quotes were gone. Tried to run same query, but getting an error.

sample data:

[{oldDate:"2022-05-23 1:28:36"}]

My query:

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $lt: [
          "$oldDate",
          "$$NOW"
        ]
      }
    }
  }
])

If the data in db is in the form of ISODate("2022-05-23 1:28:36") then this query is working. But the actual data in my db for this column is in the form of string. Can anyone help me to convert this to ISODate() through code itself and make comparison work.

CodePudding user response:

Use $toDate operator to convert date string to date.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $lt: [
          {
            $toDate: "$oldDate"
          },
          "$$NOW"
        ]
      }
    }
  }
])

Sample Mongo Playground

  • Related