MongoDB Date objects in queries

I found a working Aggregate solution using ChatGPT:

Use MongoDB’s $expr to explicitly cast the strings to dates. This approach ensures that the dates are interpreted correctly.

[
  {
    "$match": {
      "$expr": {
        "$and": [
          {
            "$gte": [
              "$example_date",
              {
                "$dateFromString": {
                  "dateString": "2023-05-01T00:00:00.000Z"
                }
              }
            ]
          },
          {
            "$lt": [
              "$example_date",
              {
                "$dateFromString": {
                  "dateString": "2023-06-01T00:00:00.000Z"
                }
              }
            ]
          }
        ]
      }
    }
  }
]