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

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

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 Report

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 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!