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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算