How to use MongoDBs aggregate `$lookup` as `findOne()`

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 ] } 
        }} 
    ]
)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)