How to do inner joining in MongoDB?

后端 未结 4 829
醉梦人生
醉梦人生 2021-02-08 02:31

Is it possible to do SQL inner joins kind of stuff in MongoDB , well i know there is

$lookup

attribute in aggregation pipeline and

4条回答
  •  既然无缘
    2021-02-08 03:05

    I found answer my self it was

    $unwind done the trick to me following query worked for me

        db.USER.aggregate([{
                $lookup: {
                    from: "USER_ROLE",
                    localField: "ID",
                    foreignField: "USER_ID",
                    as: "userRole"
                }
            }, {
                $unwind: {
                    path: "$userRole",
                    preserveNullAndEmptyArrays: false
                }
            }, {
                $lookup: {
                    from: "ROLE",
                    localField: "userRole.ROLE_ID",
                    foreignField: "ID",
                    as: "role"
                }
            }, {
                $unwind: {
                    path: "$role",
                    preserveNullAndEmptyArrays: false
                }
            }, {
                $match: {
                    "role.ROLE_NAME": "staff"
                }, {
                    $project: {
                        USER_NAME: 1,
                        _id: 0
                    }
                }
                ]).pretty()
    

    Anyway thanks for the answers

提交回复
热议问题