国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MongoDB > 正文

MongoDB中多表關(guān)聯(lián)查詢($lookup)的深入講解

2020-10-29 18:42:44
字體:
供稿:網(wǎng)友

一.  聚合框架

聚合框架是MongoDB的高級查詢語言,它允許我們通過轉(zhuǎn)換和合并多個(gè)文檔中的數(shù)據(jù)來生成新的單個(gè)文檔中不存在的信息。

聚合管道操作主要包含下面幾個(gè)部分:

命令 功能描述
$project 指定輸出文檔里的字段.
$match 選擇要處理的文檔,與fine()類似。
$limit 限制傳遞給下一步的文檔數(shù)量。
$skip 跳過一定數(shù)量的文檔。
$unwind 擴(kuò)展數(shù)組,為每個(gè)數(shù)組入口生成一個(gè)輸出文檔。
$group 根據(jù)key來分組文檔。
$sort 排序文檔。
$geoNear 選擇某個(gè)地理位置附近的的文檔。
$out 把管道的結(jié)果寫入某個(gè)集合。
$redact 控制特定數(shù)據(jù)的訪問。

$lookup

多表關(guān)聯(lián)(3.2版本新增)

在本篇幅中,我們聚焦$lookup的使用。

二.  $lookup的功能及語法

1. 主要功能 是將每個(gè)輸入待處理的文檔,經(jīng)過$lookup 階段的處理,輸出的新文檔中會包含一個(gè)新生成的數(shù)組列(戶名可根據(jù)需要命名新key的名字 )。數(shù)組列存放的數(shù)據(jù) 是 來自 被Join 集合的適配文檔,如果沒有,集合為空(即 為[ ])

2. 基本語法

{ $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the "from" collection>, as: <output array field> }}

3. 語法的解釋說明

語法值 解釋說明
from 同一個(gè)數(shù)據(jù)庫下等待被Join的集合。
localField

源集合中的match值,如果輸入的集合中,某文檔沒有 localField

這個(gè)Key(Field),在處理的過程中,會默認(rèn)為此文檔含

有 localField:null的鍵值對。

foreignField 待Join的集合的match值,如果待Join的集合中,文檔沒有foreignField
值,在處理的過程中,會默認(rèn)為此文檔含有 foreignField:null的鍵值對。
as 為輸出文檔的新增值命名。如果輸入的集合中已存在該值,則會覆蓋掉,

(注:null = null 此為真)

其語法功能類似于下面的偽SQL語句:

SELECT *, <output array field>FROM collectionWHERE <output array field> IN (SELECT *  FROM <collection to join>  WHERE <foreignField>= <collection.localField>);

三. 案例

以上的語法介紹有些枯燥,不易理解,我們直接分析品味案例好了。

假設(shè) 有 訂單集合, 存儲的測試數(shù)據(jù) 如下:

db.orders.insert([ { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 }, { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }, { "_id" : 3 }])

其中 item 對應(yīng) 數(shù)據(jù)為 商品名稱。

另外 一個(gè) 就是就是 商品庫存集合 ,存儲的測試數(shù)據(jù) 如下:

db.inventory.insert([ { "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 }, { "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 }, { "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 }, { "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 }, { "_id" : 5, "sku": null, description: "Incomplete" }, { "_id" : 6 }])

此集合中的 sku 數(shù)據(jù)等同于 訂單 集合中的 商品名稱。

在這種模式設(shè)計(jì)下,如果要查詢訂單表對應(yīng)商品的庫存情況,應(yīng)如何寫代碼呢?

很明顯這需要兩個(gè)集合Join。

場景簡單,不做贅述,直送答案 。其語句 如下:

db.orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } }])

返回的執(zhí)行結(jié)果如下:

{
    "_id" : NumberInt("1"),
    "item" : "almonds",
    "price" : NumberInt("12"),
    "quantity" : NumberInt("2"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("1"),
            "sku" : "almonds",
            "description" : "product 1",
            "instock" : NumberInt("120")
        }
    ]
}


{
    "_id" : NumberInt("2"),
    "item" : "pecans",
    "price" : NumberInt("20"),
    "quantity" : NumberInt("1"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("4"),
            "sku" : "pecans",
            "description" : "product 4",
            "instock" : NumberInt("70")
        }
    ]
}


{
    "_id" : NumberInt("3"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("5"),
            "sku" : null,
            "description" : "Incomplete"
        },
        {
            "_id" : NumberInt("6")
        }
    ]
}

分析查詢語句和結(jié)果,回扣$lookup定義,可以將上面的處理過程,描述如下:

從集合order中逐個(gè)獲取文檔處理,拿到一個(gè)文檔后,會根據(jù)localField 值 遍歷 被 Join的 inventory集合(from: "inventory"),看inventory集合文檔中 foreignField值是否與之相等。如果相等,就把符合條件的inventory文檔  整體 內(nèi)嵌到聚合框架新生成的文檔中,并且新key 統(tǒng)一命名為 inventory_docs。考慮到符合條件的文檔不唯一,這個(gè)Key對應(yīng)的Value是個(gè)數(shù)組形式。原集合中Key對應(yīng)的值為Null值或不存在時(shí),需特別小心。

四. 說明

在以下的說明中,為描述方便,將 from對應(yīng)的集合定義為 被join集合;待聚合的表成為源表; 將 localField 和 foreignField 對應(yīng)的Key 定義 比較列。

1. 因客戶端工具顯示的問題,上面示例中查詢結(jié)果重Int 類型值都自動顯示為了 NumberInt("")。這個(gè)NumberInt標(biāo)注,請忽略,不影響我們的功能測試。

2. 這個(gè)示例中,一共輸出了三個(gè)文檔,在沒有再次聚合($match)的條件下,這個(gè)輸出文檔數(shù)量是以輸入文檔的數(shù)量來決定的(由order來決定),而不是以被Join的集合(inventory)文檔數(shù)量決定。

3. 在此需要特別強(qiáng)調(diào)的是輸出的第三個(gè)文檔。在源庫中原文檔沒有要比較的列(即item值不存在,既不是Null值,也不是值為空),此時(shí) 和 被Join 集合比較,如果 被Join集合中 比較列 也恰好 為NUll 或 不存在的值,此時(shí),判斷相等 ,即會把 被Join集合中 比較列 為NUll 或 值不存在 文檔 吸收進(jìn)來。

4. 假設(shè) 源表(order) 中比較列 為某一個(gè)值,而此值在待比較表(inventory)的所有文檔中都不存在,那么查詢結(jié)果會是什么樣子呢?

order 集合在現(xiàn)有數(shù)據(jù)的基礎(chǔ)上,再被insert 進(jìn)一筆測試數(shù)據(jù),這個(gè)訂單的商品為 Start,在庫存商品中根本沒有此數(shù)據(jù)。

db.orders.insert({"_id" : 4, "item" : "Start", "price" : 2000, "quantity" : 1 })

order集合的文檔數(shù)量由之前的3個(gè)增長為4個(gè)。

再次執(zhí)行查詢

db.orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } }])

此時(shí)查看結(jié)果

{
    "_id" : NumberInt("1"),
    "item" : "almonds",
    "price" : NumberInt("12"),
    "quantity" : NumberInt("2"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("1"),
            "sku" : "almonds",
            "description" : "product 1",
            "instock" : NumberInt("120")
        }
    ]
}

{
    "_id" : NumberInt("2"),
    "item" : "pecans",
    "price" : NumberInt("20"),
    "quantity" : NumberInt("1"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("4"),
            "sku" : "pecans",
            "description" : "product 4",
            "instock" : NumberInt("70")
        }
    ]
}


{
    "_id" : NumberInt("3"),
    "inventory_docs" : [
        {
            "_id" : NumberInt("5"),
            "sku" : null,
            "description" : "Incomplete"
        },
        {
            "_id" : NumberInt("6")
        }
    ]
}


{
    "_id" : NumberInt("4"),
    "item" : "Start",
    "price" : NumberInt("2000"),
    "quantity" : NumberInt("1"),
    "inventory_docs" : [ ]
}

查詢出的結(jié)果也由之前的3個(gè)變成了4個(gè)。比較特別的是第四個(gè)文檔 ,其新增列 為 "inventory_docs" : [ ] ,即值為空 。所以,此時(shí),實(shí)現(xiàn)的功能非常像關(guān)系型數(shù)據(jù)庫的 left join。

那么,可不可以只篩選出新增列為空的文檔呢?

即 我們查詢出 ,比較列的條件下,刷選出只在A集合中,而不在集合B的文檔呢? 就像關(guān)系數(shù)據(jù)庫中量表Join的 left join on a.key =b.key where b.key is null .

答案是可以的。

其實(shí)回到聚合框架上來,再次聚合一下就可以了,來一次$match就可以了。

執(zhí)行的語句調(diào)整一下就OK了。

db.orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } }, { $match : {"inventory_docs" : [ ]} }])

執(zhí)行結(jié)果 為

{
    "_id" : NumberInt("4"),
    "item" : "Start",
    "price" : NumberInt("2000"),
    "quantity" : NumberInt("1"),
    "inventory_docs" : [ ]
}

可以看出執(zhí)行結(jié)果只有一個(gè)文檔。這個(gè)文檔表明的含義是:訂單中有這個(gè)商品,但是庫存中沒有這個(gè)商品。

($look只是聚合框架的一個(gè)stage,在其前前后后,都可以嵌入到其他的聚合管道的命令,例如$match.$group等。下面的說明5,也可以說明一二)

5. 以上的比較列都是單一的Key/Value,如果復(fù)雜一點(diǎn),如果比較的列是數(shù)組,我們又該如何關(guān)聯(lián)呢?

我們接下來再來測試一把。將之前 集合order 、inventory 插入的數(shù)據(jù)清空。

插入此場景下的新數(shù)據(jù),向order中插入的數(shù)據(jù),如下:

db.orders.insert({ "_id" : 1, "item" : "MON1003", "price" : 350, "quantity" : 2, "specs" :[ "27 inch", "Retina display", "1920x1080" ], "type" : "Monitor" })

specs 對應(yīng)的value是數(shù)組格式。

向集合inventory 新插入的數(shù)據(jù) 如下:

db.inventory.insert({ "_id" : 1, "sku" : "MON1003", "type" : "Monitor", "instock" : 120,"size" : "27 inch", "resolution" : "1920x1080" })db.inventory.insert({ "_id" : 2, "sku" : "MON1012", "type" : "Monitor", "instock" : 85,"size" : "23 inch", "resolution" : "1280x800" })db.inventory.insert({ "_id" : 3, "sku" : "MON1031", "type" : "Monitor", "instock" : 60,"size" : "23 inch", "display_type" : "LED" })

查詢的語句如下:

db.orders.aggregate([ { $unwind: "$specs" }, { $lookup:  {  from: "inventory",  localField: "specs",  foreignField: "size",  as: "inventory_docs" } }, { $match: { "inventory_docs": { $ne: [] } } }])

查詢顯示結(jié)果如下:

{
    "_id" : NumberInt("1"),
    "item" : "MON1003",
    "price" : NumberInt("350"),
    "quantity" : NumberInt("2"),
    "specs" : "27 inch",
    "type" : "Monitor",
    "inventory_docs" : [
        {
            "_id" : NumberInt("1"),
            "sku" : "MON1003",
            "type" : "Monitor",
            "instock" : NumberInt("120"),
            "size" : "27 inch",
            "resolution" : "1920x1080"
        }
    ]
}

仔細(xì)看啊,輸出文檔中的 specs 對應(yīng)的數(shù)據(jù)變成了字符串類型(原集合為數(shù)組)。是什么發(fā)揮了如此神奇功效???,請看黑板,請將目光集中在

{ $unwind: "$specs" }

還有個(gè)小問題,大家猜一下,如果查詢語句中沒有

{ $match: { "inventory_docs": { $ne: [] } } }

結(jié)果會是什么樣呢?即查看語句修改為:

db.orders.aggregate([ { $unwind: "$specs" }, { $lookup:  {  from: "inventory",  localField: "specs",  foreignField: "size",  as: "inventory_docs" } }])

大家猜猜看!

大家猜猜看!

大家猜猜看!

呵呵...此時(shí)的結(jié)果是:

文檔1
{
    "_id" : NumberInt("1"),
    "item" : "MON1003",
    "price" : NumberInt("350"),
    "quantity" : NumberInt("2"),
    "specs" : "27 inch",
    "type" : "Monitor",
    "inventory_docs" : [
        {
            "_id" : NumberInt("1"),
            "sku" : "MON1003",
            "type" : "Monitor",
            "instock" : NumberInt("120"),
            "size" : "27 inch",
            "resolution" : "1920x1080"
        }
    ]
}

文檔2
{
    "_id" : NumberInt("1"),
    "item" : "MON1003",
    "price" : NumberInt("350"),
    "quantity" : NumberInt("2"),
    "specs" : "Retina display",
    "type" : "Monitor",
    "inventory_docs" : [ ]
}

文檔3

{
    "_id" : NumberInt("1"),
    "item" : "MON1003",
    "price" : NumberInt("350"),
    "quantity" : NumberInt("2"),
    "specs" : "1920x1080",
    "type" : "Monitor",
    "inventory_docs" : [ ]
}

你推算出正確結(jié)果了嗎?

謝謝!!!

希望以上的講解和演示能對大家學(xué)習(xí)$lookup有所幫助。

注:以上案例數(shù)據(jù)參考MongoDB官方網(wǎng)站,大家也可訪問官網(wǎng)獲取更多、更全的相關(guān)知識。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對武林網(wǎng)的支持。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 孙吴县| 昭平县| 乳山市| 霍邱县| 威远县| 东港市| 大安市| 绥棱县| 太保市| 乌审旗| 同江市| 抚宁县| 阿城市| 拜城县| 兴安县| 罗定市| 兴宁市| 隆安县| 化州市| 祁东县| 定襄县| 神木县| 砚山县| 信丰县| 进贤县| 德庆县| 普兰县| 和静县| 鹤岗市| 莆田市| 新河县| 兴安盟| 南陵县| 惠安县| 阿坝| 涟水县| 夹江县| 贵德县| 萝北县| 临猗县| 敦煌市|