0

I have data as below.

[
  { num: 123, name: 'good'},
  { num: 12345, name: 'hey'},
  { num: 4523, name: 'yo' },
  { num: 777, name: 'hihi' }
]

And I want to search using regex to get some result.
For example, when I put 45, this search only 12345, 4523.

a.find({num: {$regex: req.query.q}, name: 'yo'})

But when I pass query like '45', it says "Can't use $regex with Number.".
How can I search using regex with number? Thank you so much for reading it.

1 Answer 1

3

Regex can match only when the field being matched has a stirng value, but num in your case is a number.

It says so in the Mongodb docs: https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex

However, there is a workaround using "$where" in which you can execute Javascript to return a boolean.

db.collection.find({
  $where: "/45/.test(this.num) && this.name==='yo'"
})

I tried it on mongoplayground. Try it out: https://mongoplayground.net/p/8E9kGt5moAO

To know more about how $where works, you can see the Mongodb Docs here: https://docs.mongodb.com/manual/reference/operator/query/where/#where

There is also a way to do this without $where (in MongoDb 4.2):

db.collection.find({
  $expr: {
    $and: [
      {
        $regexMatch: {
          input: {
            $toString: "$num"
          },
          regex: "45"
        }
      },
      {
        $gte: [
          "$time",
          12350
        ]
      },
      {
        $lt: [
          "$time",
          12400
        ]
      }
    ]
  }
})
Sign up to request clarification or add additional context in comments.

13 Comments

Thank you so much for your reply. But I have one more question. I want to add 'name' field more. I edited my question. How can I use multiple condition with where? And I'm using mongoose. And othere question is what implys 'test' in your case?
Edited the answer. 'test' is a function in the RegExp prototype in Javascript, so here you would use it just as you use it in JS. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Just ensure the the expression in the $where string results in a boolean
{orderTime: { $gte: ${req.query.from}T00:00:00, $lte: ${req.query.to}T23:59:59.000 }, status: { $nin: ['cancel'] }} If i have more condition with find. How can I add this conditions inside of your $where?
I have edited the mongoplayground a bit: mongoplayground.net/p/zGNJlsTkaHx Notice that I've also edited the data a bit where there are two documents with '45' in them and with name 'yo', but one of them is getting filtered out due to time.
I have one more question. Can't I use your condition with 'countDocument' of mongoose or mongodB? I got error "$where is not allowed in this context"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.