I think the previous answer has an error in the case of $ toObjectId. The let
statement is applied to the database collection in which the aggregate
function is called (ie, "Role"), and not to the collection pointed to by "from" (ie, "User").
db.role.aggregate([ { "$lookup": { "let": { "userObjId": { "$toObjectId": "$userId" } }, "from": "user", "pipeline": [ { "$match": { "$expr": { "$eq": [ "$_id", "$$userObjId" ] } } } ], "as": "userDetails" }} ])
Or
db.role.aggregate([ { "$project": { "userObjId": { "$toObjectId": "$userId" } } }, { "$lookup": { "localField": "userObjId", "from": "user", "foreignField": "$_id", "as": "userDetails" }} ])
As well as
db.user.aggregate([ { "$project": { "userStrId": { "$toString": "$_id" }}}, { "$lookup": { "localField": "userStrId", "from": "role", "foreignField": "userId", "as": "roleDetails" }} ])
source share