skip to Main Content

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

2

Answers


  1. Using aggregate you can extract $dayOfMonth and $month from initial date, filter using$match and after $project the initial document by excluding calculated day and month from the document.

    db.users.aggregate([
      {
        $addFields: {
          month: {
            $month: "$createdAt"
          },
          day: {
            $dayOfMonth: "$createdAt"
          },
          
        }
      },
      {
        $match: {
          month: 9,
          day: 11
        }
      },
      {
        $project: {
          month: 0,
          day: 0
        }
      }
    ])
    
    Login or Signup to reply.
  2. 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

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