iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
1
AI & Data

從入門到精通 MongoDB系列 第 10

Day10: NoSQL 中的關係(3) - 多對多關係

前面兩篇介紹了 MongoDB 中的兩種關係:一對一關係及一對多關係,今天要來跟大家介紹第3種關係:多對多關係


多對多關係 Many-to-Many Relationship


在上一篇介紹一對多關係的文章裡,我們使用 customer 及 order 兩個 collections 來分別儲存顧客資訊及訂單資訊,但實務上,我們應該還會有一個 collection 要拿來儲存所有商品的資訊,而透過 order 這個 collection 來連接 customer 及 product 這兩個 collections,而 customer 和 product 之間的就有了多對多關係。

  • 每個顧客可能購買很多產品
  • 每個產品可能被很多顧客購買

使用一個 collection 儲存資料

# customer
{
    "name": "Jack",
    "age": 20,
    "orders":[
    	{
            "name": "Book",
            "price": 19,
            "quantity": 2
        },
        {
            "name": "Computer",
            "price": 1999,
            "quantity": 1
        }
    ]
},
{
    "name": "Max",
    "age": 20,
    "orders":[
    	{
            "name": "Book",
            "price": 19,
            "quantity": 1
        },
        {
            "name": "Computer",
            "price": 1999,
            "quantity": 2
        }
    ]
}

我們把所有顧客資訊及訂單資訊都存在同一個 collection 會有以下的優缺點:

優點

  • 容易找到個別客戶的訂單資訊

缺點

  • 擴展性差:order 數量多,document 會太大
  • 會有很多重複資訊:name, price
  • 修改資訊不容易:修改商品名稱、價格 → 要改很多地方

分成 3 個 collections

我們分別看這三個 collections 內存的資料:

  • customer:顧客基本資訊(姓名、年齡)

  • product:產品基本資訊(名稱、價格)

  • order:訂單資訊(顧客 id、產品 id、數量)

使用這樣的儲存方式有以下的優缺點:

優點

  • 擴展性較佳:不用擔心 document 大小上限
  • 減少許多重複的產品資訊
  • 修改資訊較容易:皆只需在特定 collection 中做一次修改

缺點

  • 要查詢個別客戶的訂單資訊很麻煩 → 可使用 aggregate 聚合

一對多關係的聚合

我們一開始有兩個 collections:customer 及 order
我們可以使用以下的指令來將這兩個 collections 的資訊聚合在一起:db.customer.aggregate([{$lookup: {from: "order", localField:"orders", foreignField: "_id", as: "order_details"}}]).pretty()

這邊只示範可以使用聚合來達到以上的效果,詳細的操作跟原理,之後會有文章更深入介紹 MongoDB 的 聚合 Aggregation


這三篇文章介紹了 MongoDB 中的3種關係,分別是一對一關係、一對多關係及多對多關係的概念及操作。接下來要來介紹更進階的 CRUD 操作。


上一篇
Day09: NoSQL 中的關係(2) - 一對多關係
下一篇
Day11: 進階的 CRUD 操作(1) - insert() 與 insertMany()
系列文
從入門到精通 MongoDB26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言