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

248
Vistas
convert a $lookup result to an object instead of array

I'm doing a $lookup from a _id. So the result is always 1 document. Hence, I want the result to be an object instead an array with one item.

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {
      $project: {
        title: 1, typeCategory: "$typeCategory[0]"
      }
    }
  ]);

This notation: "$typeCategory[0]" is not working. Is there any smart way of doing this?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can just use $unwind. It deconstructs an array field from the input documents to output a document for each element

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {$unwind: '$typeCategory'},
    {
      $project: {
        title: 1, typeCategory: "$typeCategory"
      }
    }
  ]);
over 4 years ago · Santiago Trujillo Denunciar

0

You can use $arrayElemAt in $project stage.

Syntax of $arrayElemAt is { $arrayElemAt: [ <array>, <idxexOfArray> ] }

like:

mongoose.model('Discipline').aggregate([
   {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
   },
   {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
   },
   {
      $project: {
         name: 1, typeCategory: {$arrayElemAt:["$typeCategory",0]}
      }
   }
]);
over 4 years ago · Santiago Trujillo Denunciar

0

Use $first to return the first element in the array:

$project: {
    title: 1, 
    typeCategory: {$first: "$typeCategory"}
}
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