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

195
Vistas
$lookup gets all users

I'm using MongoDB(Atlas) in my project and I want to use aggregate. but I have a problem getting data.

I have two collections.

users:{
  username:'test',
  full_name:'test'
}

profiles:{
  avatar:''
}

I use this code to search users by input query

const searchedUser = await User.aggregate([
      {
        $search: {
          index: 'User',
          text: {
            query: `${query}`,
            path: {
              wildcard: '*',
            },
            fuzzy: {
              maxEdits: 2,
            },
          },
        },
      },
      {
        $project: {
          full_name: true,
          username: true,
        },
      },
      {
        $lookup: {
          from: 'profiles',
          localField: 'user',
          foreignField: 'id',
          as: 'avatar',
        },
      },

    ]);

but I get all user avatars in the array for each user. I just wanna only that user avatar.

Profile Collection Sampleenter image description here

User Collection sample enter image description here

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

0

You need to add a projection with $arrayElemAt after your $lookup like this:

const searchedUser = await User.aggregate([{
        $search: {
            index: 'User',
            text: {
                query: `${query}`,
                path: {
                    wildcard: '*',
                },
                fuzzy: {
                    maxEdits: 2,
                },
            },
        },
    },
    {
        $project: {
            full_name: true,
            username: true,
        },
    },
    {
        $lookup: {
            from: 'profiles',
            localField: 'user',
            foreignField: 'id',
            as: 'avatar',
        },
    },
    {
        $project: {
            full_name: true,
            username: true,
            avatar: {
                $arrayElemAt: ["$avatar", 0]
            }
        }
    }
]);
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