Regex under $match doesn't yield results

Viewed 37

I'm using this query :

db.getCollection('fuelings').aggregate([ 
 {
     $match: {    
                "dateCreated" : {$gte:  "2020-08-12T00:00:00.000Z" ,$lt:  "2020-08-22T12:00:00.000Z"} 
             } 
 }] ) 

Which does yields results as you can see :

enter image description here

But now I want to add another filter in $match , which filters all "status" ( from line #9) is a digit . So I've used regex :

So I've added this :

 $match: {  "status":/\d/ ,....

But now it yields 0 results :

enter image description here

Question:

Why is it happening? \d is a digit regex. why it doesn't yield results ?

1 Answers

There are couple of things missing.

  1. You are directly passing regex to match but doc says it supports only read operation query syntax. But you can use aggregate operations under $expr

  2. To handle that, you should have one of regex queries such as regexFind

  3. But those queries supports only strings

So you can convert to string using toString before matching.

  1. Playground - using find

  2. You can use $expr in $match - play

db.collection.aggregate([
  {
    $match: {
      $expr: {
        "$regexFind": {
          "input": {
            $toString: "$key"
          },
          "regex": "\\d"
        }
      }
    }
  }
])
  1. For versions before 4.2 - use regex

play

db.collection.aggregate([{
    $project:{
        key:{
            $toString:
            "$key"} 
    }
}, 
  {
    $match: {
      "key": {
        "$regex": "\\d"
      }
    }
  }
])
Related