Home > Net >  MongoDB Query: How can I aggregate an array of objects as a string
MongoDB Query: How can I aggregate an array of objects as a string

Time:01-06

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?

CodePudding user response:

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

CodePudding user response:

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

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