Relationship based Strategies
- One-to-One - Prefer key value pairs within the document
- One-to-Few - Prefer embedding
- One-to-Many - Prefer embedding
- One-to-Squillions - Prefer Referencing
- Many-to-Many - Prefer Referencing
General Rules for MongoDB Schema Design
- Rule 1: Favor embedding unless there is a compelling reason not to.
- Rule 2: Needing to access an object on its own is a compelling reason not to embed it.
- Rule 3: Avoid joins and lookups if possible, but don't be afraid if they can provide a better schema design.
- Rule 4: Arrays should not grow without bound. If there are more than a couple of hundred documents on the many side, don't embed them; if there are more than a few thousand documents on the many side, don't use an array of ObjectID references. High-cardinality arrays are a compelling reason not to embed.
- Rule 5: As always, with MongoDB, how you model your data depends entirely on your particular application's data access patterns. You want to structure your data to match the ways that your application queries and updates it.
Anti-Patterns
Below is a brief description of each of the schema design anti-patterns we've covered in this series.
- Massive arrays: storing massive, unbounded arrays in your documents.
- Massive number of collections: storing a massive number of collections (especially if they are unused or unnecessary) in your database.
- Unnecessary indexes: storing an index that is unnecessary because it is (1) rarely used if at all or (2) redundant because another compound index covers it.
- Bloated documents: storing large amounts of data together in a document when that data is not frequently accessed together.
- Separating data that is accessed together: separating data between different documents and collections that is frequently accessed together.