简体   繁体   中英

How to make regex with number in Mongodb

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.

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
        ]
      }
    ]
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM