Home > Back-end >  How to Map and reduce an array of Strings to a single object with multiple values
How to Map and reduce an array of Strings to a single object with multiple values

Time:03-06

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"
        }
    ]
}

CodePudding user response:

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

  • Related