4

I have below schema

{
 id: 123,
 values:[
   {valueId: "12444", name: "asd"},
   {valueId: "555", name: "www"},
 ]
}

i want to convert it into (combine name into single string)

{
 id: 123,
 values: "asdwww"
}

i have tried below aggregate which puts all name value in an array

$project: {
      attributes: {
        "$map": {
          "input": "$attributes",
          "as": "attr",
          "in": {
            "id": "$$attr.id",
            "values": "$$attr.values.name"
          }
        }
      }
    },

which makes it into

{
 id: 123,
 values:[
     "asd",
     "www"
   ]
}

i want to have values as single string value as "asd,www" or "asdwww"

1 Answer 1

5

You need $reduce instead of $map:

db.collection.aggregate([
    {
        $project: {
            _id: 1,
            values: {
                $reduce: {
                    input: "$values",
                    initialValue: "",
                    in: { $concat: [ "$$value", "$$this.name" ] }
                }
            }
        }
    }
])

Mongo Playground

Here's an example which shows how to handle delimiters

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.