Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
How do you apply regex to value in database to query against in mongodb?

Here is the scenario, you are storing phone numbers in mongo as a string. Values could be any of the following:

  • 987-654-3210
  • 9876543210
  • (978) 654-3210

All of these numbers are the same. I want to search using a RegExp which will basically strip the value of all non alphanumeric characters. Searching using 987-654-3210 will return 9876543210, but that's it. I'm hoping to find a solution where the regex will be applied to what is stored in the database to match the regexp that I'm passing in the query.

Ultimately, if all three of those phone numbers are in the database and the user searches using any of the three, all three should be returned.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use those 3 regex that will extract the 3 expected groups (in your example 987, 654 and 3210) :

  • XXX-XXX-XXXX : /(\d{3})-(\d{3})-(\d{4})/g
  • XXXXXXXXX : /(\d{3})(\d{3})(\d{4})/g
  • (XXX) XXX-XXXX : /\((\d{3})\)\s(\d{3})-(\d{4})/g

The idea is to generate those 3 groups from your input and generate the three format from these groups to find all documents matching any of those three formats :

var input = "987-654-3210"; // or any of the 3 formats

var regex = [];
regex[0] = /(\d{3})-(\d{3})-(\d{4})/g;      // 987-654-3210
regex[1] = /(\d{3})(\d{3})(\d{4})/g;        // 9876543210
regex[2] = /\((\d{3})\)\s(\d{3})-(\d{4})/g; // (978) 654-3210

function getPhoneNumber(phoneNumber) {
    for (key in regex) {
        var match = regex[key].exec(phoneNumber);
        if (match) {
            return match;
        }
    }
}

var group = getPhoneNumber(input);

var filter = [];
filter[0] = group[1] + "-" + group[2] + "-" + group[3];
filter[1] = group[1] + group[2] + group[3];
filter[2] = "(" + group[1] + ") " + group[2] + "-" + group[3];

db.data.find({
    "phoneNumber": {
        "$in": filter
    }
})

You can try it directly in the mongodb shell

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!