0

Is it possible to use regex on a number instead of a string?

For example: I have a field in a mongodb that contains the numeric value 1234567 (not stored as a string for sorting purposes etc.). Now I want to use regex to find parts of this number, i.e. 456.

On a database-field that contains a string "1234567" this is easy: I just pass re.compile("456") to my database query. However re.compile(456) gets me the following:

TypeError: first argument must be string or compiled pattern

Any hints on how to accomplish this? Storing my numbers as strings is not really an option, since I would lose lots of other possibilities (like gt/lt, sorting etc.).

Update: Also, I'm passing the regex right into the db-query to filter results, so I cannot pull up an individual field, convert it's content to a string and then use the regex on it.

user915245
  • 123
  • 2
  • 8

3 Answers3

2

You can convert a number to a string using the built-in str function:

str(456)
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • I wish it was that easy ;-) I can't match against a number: TypeError: expected string or buffer. And converting my numeric fields in mongodb is not an option either as mentioned above. – user915245 Sep 01 '13 at 12:53
1

Marking as duplicate: MongoDB Regex Search on Integer Value

db.test.find({ $where: "/^123.*/.test(this.example)" })
{ "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }
Community
  • 1
  • 1
planestepper
  • 3,277
  • 26
  • 38
0

This isn't possible with MongoDB. Depending on your application, you might be able to store these numbers as string-typed values instead of numbers. In Python:

db.collection.insert({"my_number": "12345678"})

For phone numbers or zipcodes where arithmetic operations like $inc don't make sense, but where you want to use a regex to search your data, this could make sense.

An alternate approach could be to store each number both as a string and as a number:

db.collection.insert({"s": "12345678", "n": 12345678})

A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70