How to use MongoDBs aggregate `$lookup` as `findOne()`
You can also use "preserveNullAndEmptyArrays"
Like so:
db.users.aggregate(
[
{ "$project": {
"fullName": {
"$concat": [ "$firstName", " ", "$lastName"]
},
"country": "$country"
}},
{ "$lookup": {
"from": "countries",
"localField": "country",
"foreignField": "_id",
"as": "countryInfo"
}},
{"$unwind": {
"path": "$countryInfo",
"preserveNullAndEmptyArrays": true
}
},
]
)
db.users.aggregate([
{
$lookup: {
from: 'countries',
localField: 'country',
foreignField: '_id',
as: 'country'
}
},
{
$unwind: '$country'
}
]).pretty()
You can use this mongo query for getting the country object
You're almost there, you need to add another $project
stage to your pipeline and use the $arrayElemAt
to return the single element in the array.
db.users.aggregate(
[
{ "$project": {
"fullName": {
"$concat": [ "$firstName", " ", "$lastName"]
},
"country": "$country"
}},
{ "$lookup": {
"from": "countries",
"localField": "country",
"foreignField": "_id",
"as": "countryInfo"
}},
{ "$project": {
"fullName": 1,
"country": 1,
"countryInfo": { "$arrayElemAt": [ "$countryInfo", 0 ] }
}}
]
)
When you don't want to repeat all fields in project, just overwrite the field in question with $addFields:
db.users.aggregate([
{ "$project": {
"fullName": {
"$concat": [ "$firstName", " ", "$lastName"]
},
"country": "$country"
}},
{ "$lookup": {
"from": "countries",
"localField": "country",
"foreignField": "_id",
"as": "countryInfo"
}},
{ "$addFields": {
"countryInfo": {
"$arrayElemAt": [ "$countryInfo", 0 ]
}
}}
])