Shaishab Roy
Shaishab Roy

Reputation: 16805

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 ?

Upvotes: 17

Views: 5440

Answers (2)

Katya Kamenieva
Katya Kamenieva

Reputation: 376

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'}}}

Upvotes: 4

arg20
arg20

Reputation: 4991

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.

Upvotes: 12

Related Questions