Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

289
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda