-2

So, I am trying to make use of $regex in my query parameter

name[$regex]="^b"

This will return bob, bake, bowen etc starting with b

But, when I use regex on columns which are INTEGER like

id[$regex]="^1"

It doesn't return 1, 11, 12, 13 ... etc even though they exist in the database. So, why does $regex fails in integer and what are the alternatives

Adshead
  • 107
  • 4
  • 10
  • Not possible till now here is the [jira](https://jira.mongodb.org/browse/SERVER-1174). – Ashh Sep 23 '18 at 05:02
  • So, is there no possible way apart from $regex to achieve same stuff? @AnthonyWinzlet – Adshead Sep 23 '18 at 05:09
  • Use `$toString` aggregation if you are using mongodb 4.0 to convert integer to string and then use `$regex` or if you are using mongodb version prior to 4.0 use`$toLower` aggregation. As done here https://stackoverflow.com/a/38672272/7510657 – Ashh Sep 23 '18 at 05:15

1 Answers1

0

The MongoDB $regex operator can only be used against string values. See the official documentation on this.

As a simple workaround, use the $where operator to test the integer:

db.example.find({ $where: "/^1/.test(this.id)" })

Inside the $where string, you can use this to reference the current document. So in your case, this.id is the id field you want.

Adam
  • 3,829
  • 1
  • 21
  • 31