如何在MongoDB中进行内部联接? [英] How to do inner joining in MongoDB?
问题描述
是否有可能在MongoDB中进行SQL内部联接, 好吧,我知道有
Is it possible to do SQL inner joins kind of stuff in MongoDB , well i know there is
$ lookup
$lookup
聚合管道中的属性,它等效于SQL中的外部联接,但我想执行与内部联接中类似的任务, 我有两个三个集合,需要将它们合并在一起
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
}
我拥有3个以上的集合,我只想提取与用户及其角色匹配的文档,而不是全部文档,我该如何在MongoDB中进行管理?有人可以给我建议吗?
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?
推荐答案
提拉米苏(Tiramisu)写道,这看起来像是架构问题.
As Tiramisu wrote this looks like schema issue.
您可以通过删除$ lookup返回空数组的文档来进行手动内部联接.
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:[]}}},
模式改变
我个人将进行架构更新,如下所示:
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"
},
这篇关于如何在MongoDB中进行内部联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!