MongoDB数据库设计准则

来源:互联网 发布:广州天拓网络 编辑:程序博客网 时间:2024/05/16 18:43

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.引用式文档
采用时机:

  1. 表现复杂的多对多关系
  2. 文档具有较大的层次数据集(一个文档最大只能存储16M)
  3. 嵌入式带来数据冗余,但是读取效率又不能远远超过数据冗余所带来的牺牲
嵌入式{   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"}
原创粉丝点击