Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 520
Shaishab Roy Avatar asked Jan 05 '17 10:01

Shaishab Roy


1 Answers

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.

like image 183
arg20 Avatar answered May 28 '23 00:05

arg20