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

176
Visualizações
Update last element of a nested array in mongodb

I have tried the below query of mongoose which does not seem to work:

Model.findOneAndUpdate(
    {
        name: origin
    },
    {
        $set: {
            'field1.$[id1].field2.-1': "value"
        }
    },
    {
        arrayFilters: [
            { 'id1.userId': "customerId" }
        ],
        new: true
    }
);

Note: field1 and field2 are arrays

The negative indexes are not accepted by MongoDB which is causing problems.

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

0

You may consider using the $set (aggregation) operator and use double $map operator:

db.collection.aggregate([
    { $match: { name: "myname" } }
    {
        $set: {
            field1: {
                $map: {
                    input: "$field1",
                    in: {
                        $cond: {
                            if: { $ne: [ "$$this.userId", "customerId" ] },
                            then: "$$this",
                            else: {
                                $mergeObjects: [
                                    "$$this",
                                    { 
                                        field2: { 
                                            $concatArrays: [
                                                { $slice: [ "$$this.field2", { $add: [ { $size: "$$this.field2" }, -1 ] } ] },
                                                ["value"]
                                            ]
                                        } 
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

over 4 years ago · Santiago Trujillo Relatório

0

Apply the $set operator together with the $ positional operator in your update to change the name field.

The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:

db.collection.update(
    { "friends.u.username": "michael" }, 
    { "$set": { "friends.$.u.name": "hello" } }
)

Answer taken from - https://stackoverflow.com/a/34431571

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