How do I apply regex to a value in a database for a query in mongodb?

Here is a script, you store phone numbers in mongo as a string. Values ​​can be as follows:

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

These numbers are all the same. I want to search with a RegExp that will basically separate the value of all non-alphanumeric characters. Searching using 987-654-3210 will return 9876543210, but it does. I am hoping to find a solution where the regex will be applied to what is stored in the database to match the regex that I pass in the request.

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

+3


source to share


1 answer


You can use these 3 regular expressions, which 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 these 3 groups from your input and generate three formats from these groups to find

all documents matching any of these 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 right in mongodb shell

+1


source







All Articles