• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

329
Vistas
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 3 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda