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"
}
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] }
}
...
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