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

143
Visualizações
Update key in nested document

I would like to update the keys of the object "values" in the following document stored in a MongoDB collection:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_Avg": 13,
            "BB_Avg": 19,
            "CC_Avg": 18
        }
    }
}

To make it looks like this:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_MT": 13,
            "BB_MT": 19,
            "CC_MT": 18
        }
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Dynamic update you can use update with aggregation pipeline starting from MongoDB 4.2,

First approach: using $rpelaceOne,

  • $objectToArray convert data.values from object to array in k and v format
  • $map to iterate loop of above converted array
  • $replaceOne will replace string on the base of input and replacement
  • $arrayToObject back to convert from array to object
db.collection.update({},
  [{
    $set: {
      "data.values": {
        $arrayToObject: {
          $map: {
            input: { $objectToArray: "$data.values" },
            in: {
              k: {
                $replaceOne: {
                  input: "$$this.k",
                  find: "Avg",
                  replacement: "MT"
                }
              },
              v: "$$this.v"
            }
          }
        }
      }
    }
  }
])

Playground


Second approach: using $split, $arrayElemAt, $concat,

Playground

over 4 years ago · Santiago Trujillo Relatório

0

You can use $rename function like this:

Is simply, you only have to say what field do you want to update and the new value.

Note that due to nested objects you have to use dot notation as explained into docs

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

db.collection.update({},
{
  "$rename": {
    "data.values.AA_Avg": "data.values.AA_MT",
    "data.values.CC_Avg": "data.values.BB_MT",
    "data.values.DD_Avg": "data.values.CC_MT"
  }
})

Example here

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