dongqiya9552 2016-11-16 20:35
浏览 367
已采纳

如何使用3个集合之间的关系进行mongoDB查询

I have these 3 mongoDB collections :

client_results

[
 'resultId':1,
 'clientId':'client00',
],
[
 'resultId':2,
 'clientId':'client00',
],

results

[
'id':1,
'siteID':5
],
[
'id':2,
'siteID':6
]

sites

[
'id':5,
'language':'ar'
],
[
'id':6,
'language':'en'
]

how I can get client_results where results.site.language = 'en' ? in MYSQL query will like this :

select cr.id, cr.clientId from client_results cr
left join results r
  on r.id = cr.resultId 
left join site s
  on s.id = r.siteID
where s.language = 'en';

but in mongoDB how I can make this query ?

thanks

  • 写回答

1条回答 默认 最新

  • dsa1230000 2016-11-17 04:56
    关注

    In mongodb it is little hectic to do joins,as mongodb was not meant to do joins,the main idea behind mongodb was to put all you need in one document,but there are some limitation,we cant put whole other document in another,anyways here is your answer,$look is like left outer join,But problem in this solution is there i have unwind the first table to join another,in this case if there is no first join there would be no second join as well, You can use a $project stage and put a _id variable in it,play with it you will get the desired result

    db.client_results.aggregate([
                                {"$lookup" : 
                                 {
                                  from : results,
                                  localField : resultId,
                                  foreignField: id,
                                  as : "resultTable"
                                }
                              },
                          {"$unwind" : "$resultTable"},
                          {"$lookup" : 
                             {
                              from : sites,
                              localField : "resultTable.siteID",
                              foreignField: id,
                              as : "siteTable"
                             }
                           },
                          {"$unwind" : "$siteTable"},
                          {$match : {"siteTable.language" : "en"}} // <-- only en language
                            ])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致
  • ¥15 禅道二次开发编辑版本,上传不了发行包