How to do inner joining in MongoDB?

本秂侑毒 提交于 2020-01-01 05:09:13

问题


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

$lookup

attribute in aggregation pipeline and it is equivalent to outer joins in SQL but i want to do a similar kind of a task as in inner joins , i have two three collections ,which i need to merge together

----User Collection----
db.User.find({})
{
   ID : 1,
   USER_NAME : "John",
   password : "pass"
}
{

   ID : 2,
   USER_NAME : "Andrew",
   PASSWORD : "andrew"
}

---ROLE COLLECTION---
db.ROLE.find({})
{
   ID : 1,
   ROLE_NAME : "admin"
},
{
    ID : 2,
    ROLE_NAME : "staff"
}

---USER_ROLE COLLECTION---
db.USER_ROLE.find({})
{
   ID : 1,
   USER_ID : 1,
   ROLE_ID : 1
}

i having above 3 collections and i want extract only the documents matched with users and their respective roles not all the documents, how can i manage it in MongoDB can anyone give me a suggestion?


回答1:


As Tiramisu wrote this looks like schema issue.

You can make a manual inner join, by removing documents where $lookup returned empty array.

....
{$lookup... as myArray},
{$match: {"myArray":{$ne:[]}}},
{$lookup... as myArray2},
{$match: {"myArray2":{$ne:[]}}},

schema change

I personally will go for schema update, like this:

db.User.find({})
{
   ID : 1,
   USER_NAME : "John",
   password : "pass"
   roles:[{ID : 1,  ROLE_NAME : "admin"}]
}


db.ROLE.find({})
{
   ID : 1,
   ROLE_NAME : "admin"
},



回答2:


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



来源:https://stackoverflow.com/questions/37575722/how-to-do-inner-joining-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!