本文為NoSQL數(shù)據(jù)模型設(shè)計(jì)系列的一部分翻屈。
引用模式用來(lái)實(shí)現(xiàn)1對(duì)多關(guān)系的引用模型
引用模式
嵌入模式會(huì)導(dǎo)致數(shù)據(jù)重復(fù)养交。例如下面publisher文檔和book文檔锨阿,publisher文檔會(huì)多次重復(fù)练对。
{
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"
}
}
使用引用模式可以消除publisher重復(fù)趟卸。
一般有兩種做法
1. 如果每個(gè)publisher的book增加不大痢法,可以將book引用放入publisher文檔中柴钻。如下
{
name: "O'Reilly Media",
founded: 1980,
location: "CA",
books: [123456789, 234567890, ...]
}
{
_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. 如果book數(shù)量變化很大凉夯,需要把publisher引用放入book文檔中货葬。如下
{
_id: "oreilly",
name: "O'Reilly Media",
founded: 1980,
location: "CA"
}
{
_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"
}
完整內(nèi)容請(qǐng)查看NoSQL數(shù)據(jù)模型設(shè)計(jì)系列