3

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

6
  • { _id: ObjectId("6222ca4252925ad4c3faec08"), { value: "test1", value: "test2" } } is not a valid json and also you cannot have the same key value in object. Please make sure your expected result is a valid json. Commented Mar 5, 2022 at 3:27
  • @YuTing sorry about that. Commented Mar 5, 2022 at 3:31
  • So the keys should be of value(N) format ? Commented Mar 5, 2022 at 5:22
  • @Dharmaraj it doesn’t have to be. Just provided example of different keys Commented Mar 5, 2022 at 5:24
  • 1
    @Dharmaraj thank you for asking effective clarification questions to support this ask! Commented Mar 5, 2022 at 19:25

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.