1

I have an array of objects where I want to make a string concatenating all of the same attributes from the array. Example:

{
    _id: 123,
    example_document: true,
    people: [
        {
            name: "John",
            age: 18
        }, {
            name: "Clint",
            age: 20
        }
    ]
}

And I wanna make a query where my result would be:

{
    _id: 123,
    example_document: true,
    people: [
        {
            name: "John",
            age: 18
        }, {
            name: "Clint",
            age: 20
        }
    ],
    concat_names: "John, Clint"
}

I think aggregate is the path I should take, but I'm not being able to find a way of getting a string out of this, only concat array elements into another array. Anyone could help?

2 Answers 2

1

You can use $concat combined with $reduce to achieve this, like so:

db.collection.aggregate([
  {
    $addFields: {
      concat_names: {
        $reduce: {
          input: "$people",
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              {
                $cond: [
                  {
                    $eq: [
                      {
                        "$strLenCP": "$$value"
                      },
                      0
                    ]
                  },
                  "",
                  ", "
                ]
              },
              "$$this.name"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

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

1 Comment

Thx a lot, it solved it
0

You can use aggregation operators $project, and $map:

db.collection.aggregate([
{
    $project:
    {
        concat_names:
        {
            $map:
            {
                input: "$people",
                as: "i",
                in: "$$i.name"
            }
        }
    }
}])

2 Comments

Can you actually use $concat with a map? I'm getting an error telling me that concat can only be used with strings, and map returns an array
Oh, concat or maybe concatArrays

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.