sarangan
sarangan

Reputation: 63

How to join for multiple collection with specific key using mongodb?

I have 3 table consider 1. User table username, email, userid, objectid 2. Role table objectid, roleid, rolename 3. User-role table objectid, roleid, userid

i need user deatils using mongoose username, email, userid, rolename need solution

Upvotes: 1

Views: 40

Answers (1)

Jahanzaib
Jahanzaib

Reputation: 116

db.users.aggregate([

    // Join with user_info table
    {
        $lookup:{
            from: "user_role",      
            localField: "userId",   
            foreignField: "userId", 
            as: "user_role"         
        }
    },
    {   $unwind:"$user_role" },     // $unwind used for getting data in object or for one record only

    // Join with user_role table
    {
        $lookup:{
            from: "role", 
            localField: "roleId", 
            foreignField: "roleId",
            as: "user_role"
        }
    },
    {   $unwind:"$role" },

    // define some conditions here 
    {
        $match:{
            $and:[{"userid" :1}]
        }
    },

    // define which fields are you want to fetch
    {   
        $project:{
            _id : 1,
            email : 1,
            userName : 1,
            userPhone : "$user_info.phone",
            role : "$user_role.role",
        } 
    }
])

Upvotes: 1

Related Questions