MongoDB的数据建模

166 阅读3分钟

The key challenge in data modeling is balancing the needs of the application, the performance characteristics of the database engine, and the data retrieval patterns. When designing data models, always consider the application usage of the data (i.e. queries, updates, and processing of the data) as well as the inherent structure of the data itself.

数据建模中的关键挑战是平衡应用程序的需求、数据库引擎的性能特征和数据检索模式。在设计数据模型时,始终要考虑应用程序对数据的使用(例如查询、更新和数据处理)以及数据本身的固有结构。

Flexible Schema 灵活的模式

Unlike SQL databases, where you must determine and declare a table's schema before inserting data, MongoDB's collections, by default, do not require their documents to have the same schema. That is:

在SQL数据库中,你必须在插入数据之前确定和声明表的模式,而MongoDB的集合在默认情况下不要求它们的文档具有相同的模式。这是:

  • The documents in a single collection do not need to have the same set of fields and the data type for a field can differ across documents within a collection.

单个集合中的文档不需要具有相同的字段集,而且集合中不同文档之间字段的数据类型也可能不同。

  • To change the structure of the documents in a collection, such as add new fields, remove existing fields, or change the field values to a new type, update the documents to the new structure.

可以更改集合中文档的结构,例如添加新字段、删除现有字段或将字段值更改为新类型,将文档更新为新结构。

This flexibility facilitates the mapping of documents to an entity or an object. Each document can match the data fields of the represented entity, even if the document has substantial variation from other documents in the collection.

这种灵活性促进了文档到实体或对象的映射。每个文档都可以匹配所表示实体的数据字段,即使该文档与集合中的其他文档有很大的差异。

In practice, however, the documents in a collection share a similar structure, and you can enforce document validation rules for a collection during update and insert operations. See Schema Validation for details.

但是,在实践中,集合中的文档共享类似的结构,你可以在更新和插入操作期间对集合执行文档验证规则。有关详细信息,请参阅模式验证。

Document Structure 文档结构

The key decision in designing data models for MongoDB applications revolves around the structure of documents and how the application represents relationships between data. MongoDB allows related data to be embedded within a single document.

决定MongoDB应用程序设计数据模型的关键是围绕文档的结构以及应用程序如何表示数据之间的关系。MongoDB允许将相关数据嵌入到单个文档中。

Embedded Data 嵌入式数据

Embedded documents capture relationships between data by storing related data in a single document structure. MongoDB documents make it possible to embed document structures in a field or array within a document. These denormalized data models allow applications to retrieve and manipulate related data in a single database operation.

嵌入式文档通过在单个文档结构中存储相关数据来表达数据之间的关系。MongoDB文档可以将文档结构嵌入到文档中的字段或数组中。这些非范式化的数据模型允许应用程序在单个数据库操作中检索和操作相关数据。

image.png

For many use cases in MongoDB, the denormalized data model is optimal.

对于MongoDB中的许多用例,非范式化的数据模型是最优的。

See Embedded Data Models for the strengths and weaknesses of embedding documents.

有关嵌入文档的优缺点,请参阅嵌入式数据模型。