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

72
Visualizações
Update field to transformed/mapped value of another field

I have a collection of, for example FieldA (string), FieldB (string). I now want to update the entire collection, such that FieldB gets set to the result of passing FieldA of the same document to a transform function, ie, something like this:

updateMany({}, ['$set': {'FieldA': myTransform('$FieldB')}])

where myTransform is a JavaScript Function. In my case, it would simply convert the string-value of FieldA to integer, as to get rid of potential leading 0s.

Obviously, this does not work: It would simply call myTransform with a constant argument of '$myField', not the actual value of the field in the current document.

How can I change this query to efficiently do what I want, ie set a field of the currently considered document to a mapped value of another field on the same document? Do I absolutely have to write two queries, one to get the values, and one to update them?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can replace your js function with $toInt in an aggregation function. After populating FieldA by $addFields, use $merge to update back to your collection.

db.collection.aggregate([
  {
    "$addFields": {
      "FieldA": {
        $toInt: "$FieldB"
      }
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])

Here is the Mongo playground for your referenc.

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