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.

1
  • 2
    Convert that field to string first using str and then apply regex on it. Commented Sep 1, 2013 at 10:15

3 Answers 3

2

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

str(456)
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

Marking as duplicate: MongoDB Regex Search on Integer Value

db.test.find({ $where: "/^123.*/.test(this.example)" })
{ "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }

3 Comments

I'm reluctant to use javascript in my query for performance-reasons. Mongodb allows regex-filtering with the $regex-operator ...any insights on how to use this instead?
Tried that, doesn't work
You should benchmark and compare against your constraints. See docs.mongodb.org/manual/core/server-side-javascript
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})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.