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

454
Visualizações
how to replace the root with object value in MongoDB

Document 1:

{
  "data": {
    "id": "123456",
    "name": "abc",
    "value": 1
  }
}

Expected Output-

{
  "abc": {
    "id": "123456",
    "name": "abc",
    "value": 1
  }
}

Explanation: How we can replace the root with the " name" value, check the expected output, whatever value of the "name", it becomes on the root level. and I have multiple documents. Thanks in advance.

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

0

You can achieve this via $project aggregation. It should be something like this:

{ $project: { "$data.name": "$data" } }
over 4 years ago · Santiago Trujillo Relatório

0

Mongo doesn't allow field names to start with a $ meaning you can't define a dynamic key name.

You'll have to work around this restriction by playing with the data structure, here is an example of how to achieve this with $arrayToObject

db.collection.aggregate([
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              k: "$data.name",
              v: "$data"
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

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