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

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

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 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