Concat array of nested documents in MongoDB

I am trying to concat some nested documents inside an array using MongoDB shell:

What I have

"id": 1,
"instructions": [
{"text": "A"},
{"text": "B"},
{"text": "C"}
]

What I want to obtain

"id" : 1
"instructions": "ABC"

What I have tried

{
        $project: {
                "instructions": {
                    $reduce: {
                        input: "$instructions.text",
                        initialValue: [],
                        in:  {
                            $concat : ["$$value", "$$this"]
                        }
                    }
                }
        }
    }

What I obtain

$concat only supports strings, not array

Upvotes: 1

Views: 349

Answers (1)

varman
varman

Reputation: 8894

What you have tried was correct. But you need to make initailValue as String, not array

{
    $project: {
      "instructions": {
        $reduce: {
          input: "$instructions",
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              "$$this.text"
            ]
          }
        }
      }
    }
  }

Working Mongo playground

Upvotes: 1

Related Questions