Database Manual / Data Modeling / Designing Your Schema

Apply Design Patterns应用设计模式

Schema design patterns are ways to optimize your data model for your application's access patterns. They improve application performance and reduce schema complexity. Schema design patterns affect how your data is stored and what data is returned to your application.模式设计模式是针对应用程序的访问模式优化数据模型的方法。它们提高了应用程序性能并降低了模式复杂性。模式设计模式会影响数据的存储方式以及返回给应用程序的数据。

For a list of schema design patterns and examples, see the Building with Patterns MongoDB blog series.有关模式设计模式和示例的列表,请参阅使用模式构建MongoDB博客系列

About this Task关于此任务

Before you implement schema design patterns, consider the problem that you are trying to solve. Each schema design pattern has different use cases and tradeoffs for data consistency, performance, and complexity. For example, some schema design patterns improve write performance, while others improve read performance.在实现模式设计模式之前,请考虑您试图解决的问题。每种模式设计模式在数据一致性、性能和复杂性方面都有不同的用例和权衡。例如,一些模式设计模式可以提高写入性能,而另一些模式可以提高读取性能。

Implementing a pattern without understanding your application and the data it needs can degrade application performance and cause unnecessary complications to your schema design.在不了解应用程序及其所需数据的情况下实现模式可能会降低应用程序性能,并给模式设计带来不必要的复杂性。

Example示例

Consider the following example patterns used by a movie theater franchise:考虑电影院特许经营使用的以下示例模式:

  • The schema contains a movie collection and a theater collection. 该模式包含一个movie(电影)集合和一个theater(剧院)集合。The schema uses the subset pattern to duplicate a subset of information from the movie collection in the theater collection. The subset pattern reduces the size of documents returned to the application and improves read performance.该模式使用子集模式theater集合中的movie集合复制信息子集。子集模式减少了返回给应用程序的文档的大小,并提高了读取性能。

  • The movie collection contains a total_views field, which uses the computed pattern to calculate a running total of the number of times that customers view a movie across all of the theaters where the movie is shown.电影集合包含一个total_views字段,该字段使用计算出的模式来计算客户在放映电影的所有影院观看电影的累计次数。

movie Collection电影集合

db.movie.insertOne(
{
_id: 1,
title: "Titanic",
year: 1997,
director: "James Cameron",
runtime: 194,
distributor: "Paramount Pictures",
languages: [ "English" ],
total_views: 3500
}
)

theater Collection剧院集合

db.theater.insertMany(
[
{
name: "Downtown Cinemas",
address: {
street: "2212 Taylor Street",
state: "NY"
},
movies: [
{
movie_id: 1,
title: "Titanic",
runtime: 194,
views: 1500
}
]
},
{
name: "Midtown Theater",
address: {
street: "1232 5th Street",
state: "NY"
},
movies: [
{
movie_id: 1,
title: "Titanic",
runtime: 194,
views: 2000
}
]
}
]
)

Learn More了解更多