0

I am storing phone numbers in the database in the user model in various formats. All the followings are possible.

+306974135662, 306974135662, 30 6974135662

Then from the front-end, I am getting a specific format that has the plus sign and no spaces.

+306974135662

I want to write a mongoid query that matches all the above formats. Is that possible?

User.where(phone: params[phone])

should return all 3 users with phone numbers +306974135662, 306974135662, and 30 6974135662

Petran
  • 7,677
  • 22
  • 65
  • 104
  • Does this answer your question? [Use LIKE/regex with variable in mongoid](https://stackoverflow.com/questions/8523111/use-like-regex-with-variable-in-mongoid) – Int'l Man Of Coding Mystery Mar 02 '21 at 19:44
  • If you know all possible formats, search for all permutations: `User.where(phone: { '$in': ['+306974135662', '306974135662', '30 6974135662'] })`. Otherwise normalise on insert. There are too many **possible** combinations to make an efficient regex. – Alex Blex Mar 02 '21 at 23:38

1 Answers1

0

Option 1: store phone numbers as they are entered, use regular expressions for matching.

Option 2: store phone numbers as they are entered in one field. In another field store canonicalized representations of the phone numbers (the second one in your example). Match against the canonicalized representation.

The second option costs additional disk space, memory and pre-processing but allows queries to be simpler and faster.

D. SM
  • 13,584
  • 3
  • 12
  • 21