Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

534
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda