如何使用mongodb使用特定键加入多个集合?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用mongodb使用特定键加入多个集合?相关的知识,希望对你有一定的参考价值。

我有3张桌子考虑1。用户表用户名,电子邮件,用户ID,对象ID2。角色表对象编号,角色编号,角色名称3。用户角色表对象ID,角色ID,用户ID

我需要使用猫鼬的用户死亡用户名,电子邮件,用户名,角色名需要解决方案

答案
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",
         
    
])

以上是关于如何使用mongodb使用特定键加入多个集合?的主要内容,如果未能解决你的问题,请参考以下文章