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.
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 atheater
collection. The schema uses the subset pattern to duplicate a subset of information from themovie
collection in thetheater
collection. The subset pattern reduces the size of documents returned to the application and improves read performance.The
movie
collection contains atotal_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.
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 } ] } ] )