skip to Main Content

I want to filter with a regex on date. I tried this:

{ createdAt: { $regex: '2021-06-25T' }}

But it doesn’t work.

How can I use a regex or something to filter for those days, on a timeStamp field?

The collections looks like this:

enter image description here

But the original JSON shows this:

{
  "_id": {
    "$oid": "60d635cb26bec4004fb19341"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1624651211668"
    }
  },
  "__v": 0
}

2

Answers


  1. You should convert the date to a string version and then apply the match. Try something like this:

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            "$regexMatch": {
              "input": {
                "$toString": "$createdAt"
              },
              "regex": "2021-06-25T"
            }
          }
        }
      }
    ])
    

    Playground link.

    Login or Signup to reply.
  2. If you want to keep everything as Dates and find documents for that specific day, you could try this.

    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$eq": [
              {
                "$dateTrunc": {
                  "date": "$createdAt",
                  "unit": "day"
                }
              },
              ISODate("2021-06-25T00:00:00Z")
            ]
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

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