MongoDB Courses - MongoDB Data Modeling Intro

MongoDB and the Document Model

Golden Principle: data that is accessed together should be stored together.

在 MongoDB 中建構資料的兩種主要方式是 embedding 和 referencing。


Embedding Data in Documents

在 document 中嵌套另一層 document,通常使用在一對多或者多對多的資料關聯。
例如:

{
name: {
firstName: "Sarah", lastName: "Davis"
}
}

優點:

  1. 將相關資料儲存在同一個 document 中。
  2. 簡化查詢並改善整體查詢效能。

缺點:

  1. 需注意過大或無限大的 document(可能超過 16 MB 的限制)。
  2. 當嵌入的 document 過大時,很難進行分頁。

Reference data in documents

雖說經常一起被讀取的資料應該要存放在一起,最單純的方式是使用 embedding,但遇到單一 document 過大時會想要將這些資料分開存放並且同時保有關聯,這時就是使用 referencing 的時機。

referencing 將一個 document 的 id field 儲存在另一個 document 裏當作是兩者之間的橋樑,有時稱作 linking 或者 data normalization

舉例

// `blog post` collection
{
_id: 1,
title: "Basics of MongoDB",
text: "Let's learn the basics of MongoDB"
}

// `comments` collection
[
{
blog_entry_id: 1, // references _id of blog post
name: "John Smith",
comment: "I learned a lot!"
},
{
blog_entry_id: 1, // references _id of blog post
name: "Jane Doe",
comment: "Looks great."
}
]

優點:

  1. 不會有資料重複
  2. 文檔較小

缺點:

  1. 需要從多個 document 中關聯資料,需要考量 query 的複雜程度以及效能