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

235
Vistas
Using a JS function and regex in MongoDB to match fields

I want to find if field_1 matches the beginning of field_2 within a document, using MongoDB Shell, and get the count of documents that matches and that does not match.

field_1 and field_2 are in the same document, and there are about 180k documents.
field_1: 2 numbers in string type (Ex. '10', '40', '15')
field_2: 8 numbers in string type (Ex. '10102020', '40204010')

Below is my code so far. It returns nothing.

db.coll_1.find().forEach(
  function(x) {
    db.coll_1.find({
      field_1: {$regex: /^x.field_2*/}
    })
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Query

  • group by null => all documents of collection as 1 group
  • 2 accumulators
    • if the first 2 characters of the field2 = field1 (n-match+1)
    • if not the first 2 characters of the field2 = field1 (n-not-match+1)

Test code here

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "n-match": {
        "$sum": {
          "$cond": [
            {
              "$eq": [
                "$field1",
                {
                  "$substrCP": [
                    "$field2",
                    0,
                    2
                  ]
                }
              ]
            },
            1,
            0
          ]
        }
      },
      "n-not-match": {
        "$sum": {
          "$cond": [
            {
              "$ne": [
                "$field1",
                {
                  "$substrCP": [
                    "$field2",
                    0,
                    2
                  ]
                }
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0
    }
  }
])
about 4 years ago · Juan Pablo Isaza 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