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

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

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