Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregate: $lookup by _id, then get first element value

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"
}
like image 751
Granga Avatar asked Aug 29 '16 22:08

Granga


1 Answers

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] }
}
...
like image 158
DAXaholic Avatar answered Sep 20 '22 17:09

DAXaholic