Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
$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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!