【问题标题】:How to join for multiple collection with specific key using mongodb?如何使用 mongodb 加入具有特定键的多个集合?
【发布时间】:2019-11-18 19:26:39
【问题描述】:

我有 3 张桌子考虑 1。用户表 用户名、电子邮件、用户 ID、对象 ID 2。角色表 对象ID、角色ID、角色名称 3。用户角色表 对象ID、角色ID、用户ID

我需要使用猫鼬的用户细节 用户名、电子邮件、用户 ID、角色名 需要解决方案

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案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",
            } 
        }
    ])
    

    【讨论】:

    • 第一次查找理解但第二次无法理解,你能解释一下上面问的表格吗
    • 一级加入,如用户 + 用户角色表已完成,但需要将用户角色加入角色表,我无法做到这一点你能帮我吗
    猜你喜欢
    • 2022-01-01
    • 2016-06-19
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多