Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading