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

260
Vistas
How to transform an array of one value into an object in $project stage?

Using mongodb, I would like to transform an array in a a document that looks like this:

{activities: [{"start": start_date, "end": end_date, value:"4332A"}]}

Into an object, like this (only projecting the value field as the value of "activities"):

{activities: "4332A"}

I have tried using $arrayToObject in the $project stage, but the results is not really what I am looking for :

    db.companies.aggregate([{
        $project: {
            $map: {
                'input': '$activities',
                'as': 'item',
                'in': {
                    'k': 'activities',
                    'v': '$$item.value'
                }
            }
        }
    ])

The output being:

{"activities": {"activities": "4332A"}}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Assuming there is always exactly one result in the array ( as you said ), you can just use arrayElemAt, like so:

db.collection.aggregate([
  {
    $addFields: {
      activities: {
        "$arrayElemAt": [
          "$activities.value",
          0
        ]
      }
    }
  }
])

Mongo Playground

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