如何在两个集合之间建立查找连接

时间:2019-11-02 13:20:41

标签: sql mongodb mongodb-query aggregation-framework

目标:
此sql及其结果应与mongoDB的查询代码中的结果相同。
 换句话说,对于mongoDB,结果相同。

问题:
如何在Mongo DB的查询代码中建立与角色相关的查找连接?

信息:
我是mongo DB的新手

SQL code 
    SELECT 
        a.*,
        '.' AS '.',
        b.*,
        '.'  AS '.',
        c.*
    FROM 
        [db1].[dbo].[People_Course_Grade] a
        INNER JOIN [db1].[dbo].[People] b on a.PeopleId = b.PeopleId
        INNER JOIN [db1].[dbo].[Role] c on b.RoleId = c.RoleId

enter image description here

Json数据:

Role:  
[{"RoleId":1,"Name":"Student"},{"RoleId":2,"Name":"Teacher"}]

People_Course_Grade:   
[{"People_Course_GradeId":1,"PeopleId":1,"CourseId":1}, 
 {"People_Course_GradeId":2,"PeopleId":2,"CourseId":1}, 
 {"People_Course_GradeId":3,"PeopleId":3,"CourseId":2}, 
 {"People_Course_GradeId":4,"PeopleId":1,"CourseId":2}]

Course:
[{"CourseId":1,"Name":"Java"},{"CourseId":2,"Name":"Java II"}, 
 {"CourseId":3,"Name":"Statistik 1"}]

Mongo db

db.People_Course_Grade.aggregate([

    {
        $lookup:{
            from: "People",            
            localField: "people_id",   
            foreignField: "_id",       
            as: "people"               
        }
    },
    {   $unwind:"$people" },   


    {   
        $project:{
            course_id : 1,
            people_id : 1,
      //      grade_id : 1,
            Name : "$people.Name",


        } 
    }

]);

1 个答案:

答案 0 :(得分:0)

由于您有三个集合,因此需要从双$lookup开始。然后,您可以使用$arrayElemAt始终从查找结果中获取单个元素。要使结构扁平化,可以将$replaceRoot$mergeObjects一起使用(将所有字段从peoplecourse提升到根级别。

db.People_Course_Grade.aggregate([
    {
        $lookup:{
            from: "Role",            
            localField: "PeopleId",   
            foreignField: "RoleId",       
            as: "people"               
        }
    },
    {
        $lookup:{
            from: "Course",            
            localField: "CourseId",   
            foreignField: "CourseId",       
            as: "course"               
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [
                    "$$ROOT",
                    { $arrayElemAt: [ "$people", 0 ] },
                    { $arrayElemAt: [ "$course", 0 ] },
                ]
            }
        }
    },
    {
        $project: {
            people: 0,
            course: 0
        }
    }
])

Mongo Playground

$arrayElemAt始终可以像您尝试的那样用$unwind代替。您在name字段上还存在命名冲突,因此可能需要运行$project重命名这些字段之一-否则最终结果中只会得到其中一个。