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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With