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

145
Visualizações
How to Map and reduce an array of Strings to a single object with multiple values

I have a document that looks like such:

{
  _id: ObjectId("6222ca4252925ad4c3faec08"),
  value: ["test1","test2"]
}

I would like to get:

{
  _id: ObjectId("6222ca4252925ad4c3faec08"),
 “value”:
    {  
      “value1”: "test1",
      “value2”: "test2"
     }
}

I have tried to use reduce but I get each value in one object but am very close. Please let me know what I am doing wrong:

Code:

{
  "$project": {
    "value": {
      $reduce: {
        input: "$value",
        initialValue: [],
        in: {$concatArrays: [
          "$$value", 
          [{"name": "$$this"}]
        ]}
      }
    }
  }
}

Results:

{ 
    "_id" : ObjectId("6222ca4252925ad4c3faec08"), 
    "value" : [
        {
            "name" : "test1"
        }, 
        {
            "name" : "test2"
        }
    ]
}

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

0

Currently you are just creating an array using $reduce, Instead you can try using $map to create an array of format [key, value] and then use $arrayToObject to convert that to a map as shown below:

[
  {
    "$project": {
      "provider": {
        "$arrayToObject": {
          "$map": {
            "input": "$value",
            "as": "v",
            "in": [
              {
                "$concat": [
                  "value",
                  {
                    "$toString": {
                      "$indexOfArray": [
                        "$value",
                        "$$v"
                      ]
                    }
                  }
                ]
              },
              "$$v"
            ]
          }
        }
      }
    }
  }
]

The $indexOfArray is just to get key of format value(N).

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