Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!