1

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

1 Answer 1

1
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",
        } 
    }
])
Sign up to request clarification or add additional context in comments.

2 Comments

first lookup understood but second one not able to understand, can u explain above asked table wise
First level join like user + user role table done but need to join user role with role table i am not able to do can u help me on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.