且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MongoDB 中进行内部连接?

更新时间:2022-10-31 15:53:37

正如 Tiramisu 所写,这看起来像是架构问题.

您可以通过删除 $lookup 返回空数组的文档来进行手动内部联接.

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

架构变更

我个人会进行架构更新,如下所示:

db.User.find({}){编号 : 1,USER_NAME:约翰",密码:通过"角色:[{ID:1,ROLE_NAME:管理员"}]}db.ROLE.find({}){编号 : 1,ROLE_NAME:管理员"},

Is it possible to do SQL inner joins kind of stuff in MongoDB?

I know there is the $lookup attribute in an aggregation pipeline and it is equivalent to outer joins in SQL, but I want to do something similar to inner joins.

I have three collections which need to merge together:

// User Collection
db.User.find({});

// Output:
{
   ID : 1,
   USER_NAME : "John",
   password : "pass"
}
{

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

// Role Collection
db.ROLE.find({});

// Output:
{
   ID : 1,
   ROLE_NAME : "admin"
},
{
    ID : 2,
    ROLE_NAME : "staff"
}

// USER_ROLE Collection
db.USER_ROLE.find({});

// Output:
{
   ID : 1,
   USER_ID : 1,
   ROLE_ID : 1
}

I have the above collections and I want to extract only the documents matched with users and their respective roles, not all the documents. How can I manage it in MongoDB?

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"
},