Filter Data between two String

304 views Asked by At

I have a creation date attribute of a document which has a format like this: "05/03/2020" of type String.

I must extract all the documents from my system having a creation date before "05/03/2020".

I tried with:

db.MyCollection.find ({DateC: {$lte: "05/03/2020"}})

but it still returns 0.

Is there a way to compare if a date format String is before another date?

Thank you

1

There are 1 answers

0
turivishal On BEST ANSWER

You can use $dateFromString operator to convert $DateC to ISODate,

  • Make sure your input should be in ISODate format,
db.MyCollection.find([
  {
    $expr: {
      $lte: [
        {
          $dateFromString: {
            dateString: "$DateC",
            format: "%d/%m/%Y"
          }
        },
        ISODate("2020-03-05T00:00:00.000Z")
      ]
    }
  }
])

Playground

I am not sure with your date format, I have predicted as d/m/y, you can manage it your self if its different.