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

626
Vistas
How to return single object instead of array in $lookup of MongoDB?

When we use $lookup in aggregate query of MongoDB we use this format

{
   $lookup:
     {
       from: "users",
       localField: "userId",
       foreignField: "_id",
       as: "user"
     }
}

where user return as an array of object and then some time we need to use $arrayElemAt in $project stage to return as a single object. like

{
  $project:
   {
    user:
      { 
        $arrayElemAt: [ "$user", 0 ] 
      }
   }
}

so my question is how can we return user as a single object instead of array from $lookup stage ?

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

0

You can't do that with $lookup yet, the cleanest way to do it would be to add a new stage afterwards like this:

{
  $unwind: "$user"
}

Since each document has only one user you end up with the same collection but this time user is no longer an array. If you had more than one user per document (e.g 2), you would end up with 2 documents one with each user.

over 4 years ago · Santiago Trujillo Denunciar

0

You cannot return object as the output of $lookup, you can use the subsequent stage $set to overwrite the existing 'user' field (similar to what you did with $project)

{$set: {'user': {$first: '$user'}}}
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