Search code examples
regexdatabasemongodbmongoosefind

MongoDB find document with Date field using a part of Date


i want to search a date like the following:

09-11
03-22

and it will search in the available documents and bring the matched documnet. an available document example :

2022-09-11T15:31:25.083+00:00

how can i do this?

i tried following query but that didn't work:

db.users.find({ createdAt: new RegExp('09-11') }) // Null

Solution

  • You can do it with aggregate query:

    • $toString - to convert date to string
    • $regexMatch - to apply regex search
    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$regexMatch": {
              "input": {
                "$toString": "$createdAt"
              },
              "regex": "09-11"
            }
          }
        }
      }
    ])
    

    Working example