HOWTO · MongoDB

使用 MongoDB `$lookup` 管道連接文件

使用 MongoDB `$lookup` 管道,依 `shopId` 連接文件、要求連接的文件缺少指定欄位,並篩除沒有相符結果的文件。

本頁內容

在 MongoDB 的 $lookup 階段中使用管道,當 shopId 值相符,且 collection1 文件沒有 shopPosId 欄位時,便將 collection2 的文件與 collection1 的文件連接。$lookup 會執行左外部連接,因此 collection2 的每筆輸入文件都會保留在結果中;沒有相符文件的資料列,其 shopDescription 陣列會是空的。若只想保留有連接到文件的資料列,可以再加入 $match 階段。

什麼是聚合管道

聚合管道會依序透過各個階段處理文件。每個階段都能篩選或調整輸入內容,再將結果傳給下一個階段。在此範例中,$lookup 會加入相符的文件,後續的 $match 則可篩選連接結果。MongoDB 也提供 map-reduce 和單一用途的聚合操作,但這個連接範例不需要用到它們。

如需更多說明,請參閱 MongoDB 聚合管道概覽。

什麼是 MongoDB 中的 $lookup 運算子

$lookup 會連接同一資料庫中另一個集合的文件,並將相符文件寫入陣列欄位。from 選項指定要查找的集合,as 則指定要新增至每筆輸入文件的陣列欄位名稱。使用管道形式時,可以對要連接的文件套用條件。

MongoDB $lookup 參考文件列出可用的語法形式。下方範例使用相關管道:let 會將輸入文件中的值提供給該管道,而 $expr 讓 $match 能使用這個值比較欄位。本文中的 MongoDB shell 指令是供讀者在 MongoDB 資料庫中執行的範例;設定好的文章執行環境不會執行資料庫操作。

在 MongoDB 中使用 $lookup 管道搭配條件連接文件

使用下列文件建立 collection1 和 collection2。以下以 MongoDB shell 示範設定方式;請在 mongosh 中,對想使用的資料庫逐一執行各項陳述式。

db.createCollection('collection1'); db.createCollection('collection2'); db.collection1.insertMany([{"shopId":"001","shopPosId":"001","description":"description for 001"},{"shopId":"002","description":"description for 002"},{"shopId":"003","shopPosId":"003","description":"description for 003"},{"shopId":"004","description":"description for 004"}]); db.collection2.insertMany([{"shopId":"001","shopPosId":"0078","clientUid":"474192"},{"shopId":"002","shopPosId":"0012","clientUid":"474193"},{"shopId":"003","shopPosId":"0034","clientUid":"474194"},{"shopId":"004","shopPosId":"0056","clientUid":"474195"}]);

接下來的獨立 Python 範例會模擬相同的範例資料比對結果:002 和 004 會取得連接後的描述,因為它們在 collection1 中的文件具有相符的 shopId,且缺少 shopPosId。這段程式只用來說明結果邏輯,並不是 MongoDB 查詢。範例及其輸出中可見的文字(如 “description for 002”)保持英文,不作翻譯。

執行此範例:

collection1 = [
    {"shopId": "001", "shopPosId": "001", "description": "description for 001"},
    {"shopId": "002", "description": "description for 002"},
    {"shopId": "003", "shopPosId": "003", "description": "description for 003"},
    {"shopId": "004", "description": "description for 004"},
]
collection2 = [
    {"shopId": "001", "shopPosId": "0078", "clientUid": "474192"},
    {"shopId": "002", "shopPosId": "0012", "clientUid": "474193"},
    {"shopId": "003", "shopPosId": "0034", "clientUid": "474194"},
    {"shopId": "004", "shopPosId": "0056", "clientUid": "474195"},
]

for source in collection2:
    matches = [
        item["description"]
        for item in collection1
        if item["shopId"] == source["shopId"] and "shopPosId" not in item
    ]
    print(f'{source["shopId"]}: {matches}')
001: []
002: ['description for 002']
003: []
004: ['description for 004']

在 MongoDB 管道中設定 let: {shopId: "$shopId"},將每筆 collection2 資料列的 ID 傳入查找管道。使用 $expr: {$eq: ["$shopId", "$$shopId"]} 進行比對;$$ 前綴表示這是由 let 定義的變數。再於 $and 中加入 {shopPosId: {$exists: false}},要求連接的 collection1 文件沒有該欄位。

對應的第一個查詢是 db.collection2.aggregate([{$lookup: {from: "collection1", let: {shopId: "$shopId"}, pipeline: [{$match: {$and: [{$expr: {$eq: ["$shopId", "$$shopId"]}}, {shopPosId: {$exists: false}}]}}], as: "shopDescription"}}])。這會保留全部四筆 collection2 輸入。001 和 003 沒有符合條件的 collection1 文件,因此它們的 shopDescription 陣列為空;002 和 004 則相符,因為連接到的文件都缺少 shopPosId。

若只要傳回有相符文件的資料列,可附加 $match 階段,檢查連接後的陣列至少包含一個項目:{$match: {shopDescription: {$ne: []}}}。完整的後續查詢為 db.collection2.aggregate([{$lookup: {from: "collection1", let: {shopId: "$shopId"}, pipeline: [{$match: {$and: [{$expr: {$eq: ["$shopId", "$$shopId"]}}, {shopPosId: {$exists: false}}]}}], as: "shopDescription"}}, {$match: {shopDescription: {$ne: []}}}])。依照範例資料,這會傳回商店 002 和 004 的來源資料列。第一個 $lookup 階段仍是左外部連接;第二個階段才會移除連接陣列為空的資料列。範例中的程式碼與輸出標籤維持英文。