Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

299
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda