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

149
Vistas
How to set existing field and their value to array's objects

I'm new to MongoDB. I've an object below

{
        "_id" : "ABCDEFGH1234",
        "level" : 0.6,
        "pumps" : [
                {
                        "pumpNo" : 1
                },
                {
                        "pumpNo" : 2
                }
        ]
}

And I just want to move level field to pumps array's objects like this

{
        "_id" : "ABCDEFGH1234",
        "pumps" : [
                {
                        "pumpNo" : 1,
                        "level" : 0.6
                },
                {
                        "pumpNo" : 2,
                        "level" : 0.6
                }
        ]
}

I've check on MongoDB doc in Aggregation section but didn't found anything. In SQL by JOIN or SUB Query I'm able to do but here it's No-SQL

Could you please help me with this? Thankyou

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Try this on for size:

db.foo.aggregate([
    //  Run the existing pumps array through $map and for each                                      
    //  item (the "in" clause), create a doc with the existing                                      
    //  pumpNo and bring in the level field from doc.  All "peer"                                   
    //  fields to 'pumps' are addressable as $field.                                                
    //  By $projecting to a same-named field (pumps), we effectively                                
    //  overwrite the old pumps array with the new.                                                 
    {$project: {pumps: {$map: {
        input: "$pumps",
        as: "z",
        in: {pumpNo:"$$z.pumpNo", level:"$level"}
        }}  
    }}
]);

Strongly recommend you explore the power of $map, $reduce, $concatArrays, $slice, and other array functions that make MongoDB query language different from the more scalar-based approach in SQL.

over 4 years ago · Santiago Trujillo 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