表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