我希望它可以帮助像你一样有类似需求的人。
MongoDB 中的模式设计和数据建模
数据建模的观点
- 概念数据建模:关于功能和服务的大图,其中还包括
- ER 数据建模:数据库设计的图形化方法。
- 架构设计
- 逻辑数据建模:概念数据建模将使用编程语言、表格等转换为逻辑数据建模(程序)。(服务器代码)
- 物理数据建模:将逻辑 DM 付诸实践,实际数据由用户插入。(数据库)
数据模型的类型
文档之间的模型关系
- 通常,您应该构建您的模式,以便您的应用程序在一次读取操作中接收所有所需的信息。
使用嵌入式文档建模一对一关系
- In referenced or normalized data model, If one document is frequetly refering some data in another document, It would create better data model to embed both documents into one.
- If a single document seems to be large, it is better split your data into referential model, the most frequently-accessed portion of the data should go in the collection that the application loads first
```json
// one person and one address
{
_id: "joe",
name: "Joe Bookreader",
address: {
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
}
```
使用嵌入式文档建模一对多关系
// one person and his multiple address
{
"_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"
}
]
}
使用参考文档建模一对多关系
- 在某些情况下,最好使用参考模型来获得更好的性能,如下所示。
- 为避免出版商数据重复,请使用参考资料并将出版商信息保存在与图书收藏不同的收藏中。
{
_id: 'some string'
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"
}
- 如果将来书籍数组有可能变得庞大,最好将出版商引用存储在书籍文档中。
- 观察架构中的智能变化,
_id
信息(即出版商 ID)如何在 BOOK COLLECTION 中被称为publisher_id
.
{
_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"
}