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

363
Visualizações
MongoDB Add Field in nested array by other field

Hello i have simple collection:

{
    _id: 1,
    books: [
         { bookId: 55, c: 5},
         { bookId: 66, c: 6},
         { bookId: 77, c: 7},
    ]
}

How i can add new field by calulate other field? here i add field “Z” to current found object in nested array by it calculate field “C”

updateOne(
{ 
  _id : 1, 
  'books.bookId' : 66 
} ,
{
  [
      {    $addFields: { "books.$.z" : { "$sum" : ["$books.$.c", 1]  } }    }
  ]
}

Expected result:

{
    _id: 1,
    books: [
         { bookId: 55, c: 5},
         { bookId: 66, c: 6, z:7},
         { bookId: 77, c: 7},
    ]
}

I think there is a short entry (possibly using new $getField ?!), I think mango is still able to combine ‘position operator $’ + (‘varible operator reference by prefix $’ or ‘combine with $getField’) how i try in my sample

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use the aggregation pipeline in the update method to leverage the operators $map, $mergeObjects and $cond to achieve the desired results:

.updateOne(
    // The query will find docs where *at least* one bookId in the
    // books array equals 66 -- but remember it does not pinpoint
    // the location in the array!  We will tackle that in the update
    // pipeline to follow...
    { _id: 1, 'books.bookId': 66 },
    [
        { $set: {
            books: {
                $map: {
                    input: '$books',
                    in: {
                        $mergeObjects: [
                            '$$this',
                            {
                                $cond: [
                                    { $eq: ['$$this.bookId', 66] }, // IF books.bookId == 66
                                    { z: { $sum: ['$$this.c', 1] } }, // THEN merge a new field 'z' with calced value
                                    null  // ELSE merge null (a noop)
                                ]
                            }
                        ]
                    }
                }
            }
        } }    
    ]
)
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