Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo how to find field excluding special chars

I have this Mongo document

{
    _id: ObjectId('6616851ed50d6d1451fa8176'),
  phone: "+7(926)458-54-52",
  name: "Aboba"
}

I want to find that document if user inputs 7926, but also my filter is filtering another field as well.

I am filtering with regex phone or name but phone contains "+" and "()" so if user input is 7926, it wont be found.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I resolve that?

My regex:

{'$regex': f'\\w*{request_value}\\w*', '$options': 'i'}

I am filtering like that:

{$or: [name: regex, phone: regex}

>Solution :

Firstly, I agree with Ray’s answer.

create a sanitized string, named phoneForSearch

That would allow you to also index and search better against it.

However, if you reeeaally want to just ignore special chars, then you can do something like this:

For phone numbers, separate each digit with \D* which is "one or more non-digits". First add the \D between all digits in your app/code and then search with that as a regex. So a search for 7926 against an unclean phone number could be done as:

db.collection.find({
  phone: {
    $regex: "\\D*7\\D*9\\D*2\\D*6\\D*",
    $options: "i"
  }
})

That also matches against other non-numbers like:

+7(926)458-54-52
+7===+++|||9....2++++6458-54-52
+7ssss9xxxx2yyyy6dddd-458-54-52
+7===+++|||9....2++++6458-54-52

which is why it’s better to NOT do something like that.
Mongo Playground

And if you want to handle that \D insertion in Mongo, you can do it like this:

(updating)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading