Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

538
Views
MongoDB Query: How can I aggregate an array of objects as a string

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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

db.collection.aggregate([
{
    $project:
    {
        concat_names:
        {
            $map:
            {
                input: "$people",
                as: "i",
                in: "$$i.name"
            }
        }
    }
}])
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!