Jacques Gingras
Jacques Gingras

Reputation: 53

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:

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.

Upvotes: 3

Views: 281

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45362

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

Upvotes: 1

Related Questions