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

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

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