表A:

id name
---------------------------
1 Tom
2 Roger
3 Mars
4 Brent

表B:

id result
-------------------------
1 90
2 60
3 88
4 75

需求

将表A中的name和表B中的result关联查询。

思路

通过关联条件id关联name和result

mysql 用left join,mongo用$lookup

语句

db."A表".aggregate([
    {
        "$lookup": {                   //通过loolup关联两个表,相当于left join 
            "from": "B表",             //同一个数据库下需要被关联的集合名
            "localField": "A_id",      //A表需要关联的键
            "foreignField": "B_id",    //B表需要关联的键
            "as": "B_list"             //B表的别名,下面输出B表字段时用到
        }
    },
    {
        "$match": {
            "A_id": '1'               //查询条件,相当于where
        }
    },
    {
        "$project": {                      //决定要显示的字段,相当于select的作用
            "name": 1,
            "B_result": "$B_list.result"
        }
    }])

 

结果

name B_result
---------------------------------

Tom 90

注意

1 只能两个表联合查询
2 不能跨库联合

更复杂的查询:https://www.cnblogs.com/xuliuzai/p/10055535.html

 

相关文章:

  • 2022-02-07
  • 2021-05-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案