With MongoDB 3.4, you can run an aggregation pipeline that uses the $addFields
pipeline and a $filter
operator to only return the Company
array with elements that match the given condition. You can then wrap the $filter
expression with the $arrayElemAt
operator to return a single document which in essence incorporates the $unwind
functionality by flattening the array.
Follow this example to understand the above concept:
db.users.aggregate([
{ "$match": { "UserName": "administrator" } },
{
"$lookup": {
"from": 'companies',
"localField": 'CompanyID',
"foreignField": 'CompanyID',
"as": 'Company'
}
},
{
"$addFields": {
"Company": {
"$arrayElemAt": [
{
"$filter": {
"input": "$Company",
"as": "comp",
"cond": {
"$eq": [ "$$comp.CompanyName", "edt5" ]
}
}
}, 0
]
}
}
}
])