1.嵌入式文檔
如果需要在其它文檔上下文(父文檔)查看某個數據,則選擇把該數據嵌入指定上下文中。
例如:在應用中,地址信息通常不是單獨顯示而是隨着個人信息一起顯示,在這種場景之下應該採用嵌入式文檔。
{
_id: "joe",
name: "Joe Bookreader",
addresses: [
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
},
{
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}
]
}
優點:檢索該文檔的全部信息只用一次查詢即可。
2.引用式文檔
採用時機:
- 表現複雜的多對多關係
- 文檔具有較大的層次數據集(一個文檔最大隻能存儲16M)
- 嵌入式帶來數據冗餘,但是讀取效率又不能遠遠超過數據冗餘所帶來的犧牲
嵌入式
{
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher: {
name: "O'Reilly Media",
founded: 1980,
location: "CA"
}
}
{
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English",
publisher: {
name: "O'Reilly Media",
founded: 1980,
location: "CA"
}
}
上述模型造成了發佈者數據重複,爲了改善這種情況可採用引用式。引用式又分兩種情況:
1.多的一端只是許多,不是特多,有數量範圍的,則可以把引用放在發佈者一端
**publisher**
{
name: "O'Reilly Media",
founded: 1980,
location: "CA",
books: [123456789, 234567890, ...]
}
**book**
{
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English"
}
{
_id: 234567890,
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English"
}
2.多的一端,數量極大,無法估量。則將”one”端的引用放在”many”的一端
**publisher**
{
_id: "oreilly",
name: "O'Reilly Media",
founded: 1980,
location: "CA"
}
**book**
{
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly"
}
{
_id: 234567890,
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English",
publisher_id: "oreilly"
}