Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I want to join more than two collections in MongoDB using the aggregate $lookup. Is it possible to join? Give me some examples.

Here I have three collections:

"users"

"_id" : ObjectId("5684f3c454b1fd6926c324fd"), 

"email" : "[email protected]", 

"userId" : "AD", 

"userName" : "admin" 

}

"userinfo"

"_id" : ObjectId("56d82612b63f1c31cf906003"), 

"userId" : "AD", 

"phone" : "0000000000" 

}

"userrole"

"_id" : ObjectId("56d82612b63f1c31cf906003"), 

"userId" : "AD", 

"role" : "admin" 

}

1 Answer

0 votes
by (106k points)

To join multiple collections with $lookup in mongodb you can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([ 

{ $lookup: { 

from: "sivaUserRole", 

localField: "userId", 

foreignField: "userId", 

as: "userRole" 

 } 

}, 

$unwind: "$userRole" 

}, 

$lookup: { 

from: "sivaUserInfo", 

localField: "userId", 

foreignField: "userId", 

as: "userInfo" 

}, 

$unwind: "$userInfo" 

}

 ])

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...