NoSQL数据模型设计 - 关系数据建模 - 引用模型实现1对多

2020-09-25  本文已影响0人  李桐2000

本文为NoSQL数据模型设计系列的一部分。

引用模式用来实现1对多关系的引用模型

引用模式

嵌入模式会导致数据重复。例如下面publisher文档和book文档,publisher文档会多次重复。

{
   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重复。

一般有两种做法

1. 如果每个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数量变化很大,需要把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"
}

完整内容请查看NoSQL数据模型设计系列

上一篇下一篇

猜你喜欢

热点阅读