16

When I do $lookup, in my case the foreignField:"_id", I get the found element in an array. Here is one document from the output after $lookup has been done to retrieve fromUser and toUser from the users collection:

{ 
    _id : { from : 57b8da368e4a6e1f0043cb3d, to : 57c381af7008e51f009d92df }, 
    fromUser : [
        {
            _id : 57b8da368e4a6e1f0043cb3d, 
            userName: "A"
        }
    ], 
    toUser : [
        {
            _id : 57c381af7008e51f009d92df, 
            userName: "B"
        }
    ]
}

As you can notice fromUser and toUser are arrays. How to project fromUser and toUser so instead of arrays they contain just the user's userName, like here:

{
    _id : { from : 57b8da368e4a6e1f0043cb3d, to : 57c381af7008e51f009d92df },
    fromUser: "A",
    toUser: "B"
}
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
Granga
  • 1,612
  • 1
  • 14
  • 20

2 Answers2

46

You can achieve that by appending a $project stage using the $arrayElemAt operator to your aggregation pipeline like this

// your previous stages incl. lookup
...
$project: {
    fromUser: { $arrayElemAt: ["$fromUser.userName", 0] },
    toUser: { $arrayElemAt: ["$toUser.userName", 0] }
}
...
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
6

If you want to get the first element in array, then you can use $first operator and its simple to use.

{
    $set: {
        fromUser: {
            $first: "$fromUser.userName" 
        },
        toUser: {
            $first: "$toUser.userName" 
        }
    }
}

If you want to get other than first element in an array, then you can use $arrayElemAt operator.