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

118
Visualizações
MongoDB: append as field the matched element from array

I have the following code:

const array = ['a', 'b', 'c']

await collection.aggregate([
  { 
    $match: { 
      codes: { $in: array } 
    }
  },
  { 
    $addFields: { matchedField: "codes.$" } // <--- does not work
  }, 
]).toArray();

I need to append the matched element from within array to the returned results. Is it possible to do that?

My collection contains documents with the following scheme:

{
  "color": "red",
  "codes": [ "b" ]
}

I need the aggregation directive to return this:

{
  "color": "red",
  "codes": [ "b" ],
  "matchedField": "b",
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

$filter

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $filter: {
          input: "$codes",
          as: "c",
          cond: {
            $in: [
              "$$c",
              [
                "a",
                "b",
                "c"
              ]
            ]
          }
        }
      }
    }
  }
])

mongoplayground


$setIntersection

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $setIntersection: [
          "$codes",
          [
            "a",
            "b",
            "c"
          ]
        ]
      }
    }
  }
])

mongoplayground

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