9. Schema Design
Normalized schema
01. Order = {
02. _id : orderId, Order
03. user : userInfo, • _id
04. items : [
• user
05. productId1, • items *
06. productId2,
07. productId3
08. ] Product
09. } • _id
10. Product = { • name
11. _id: productId, • price
12. name : name, • desc
13. price : price,
14. desc : description * Link to collection of product
15. }
10. Schema Design
Normalized schema
• Normalized documents are a perfectably
acceptable way to use MongoDB.
• Normalized documents provide maximum
flexibility.
11. Schema Design
Links across documents
DBRef
{ $ref : <collname>, $id : <idvalue>[, $db : <dbname>] }
Or simple storage of _id..
12. Schema Design
Denormalized schema
01. Order = {
02. _id : orderId, Order
03. user : userInfo, • _id
04. items : [ {
• user
05. _id: productId1, • items
06. name : name1,
07. price : price1 • _id
• name
08. }, {
• price
09. _id: productId2,
10. name : name2, • _id
11. price : price3 • name
12. }] • price
13. }
13. Schema Design
Denormalized schema
• Embedded documents are good for fast queries.
• The embedded documents always available with
the parent documents.
• Embedded and nested documents are good for
storing complex hierarchies.
17. Schema Design
Also indexes..
The _id Index
• Automatically created except capped collection
• Index is special and cannot be deleted
• Enforces uniqueness for its keys
Indexing Array Elements
• Indexes for each element of the array
Compound Keys
• Direction of the index ( 1 for ascending or -1 for descending )
18. Schema Design
Again indexes...
Create options
sparse, unique, dropDups, background, v…
Geospatial Indexing
> db.places.ensureIndex( { loc : "2d" } )
> db.places.ensureIndex( { loc : "2d" } , { min : -500 , max : 500 } )
> db.places.ensureIndex( { loc : "2d" } , { bits : 26 } )
19. Schema Design
Analysis and Optimization
Profiler | Explain
20. Schema Design
Database Profiler
Profiling Level
• 0 - Off
• 1 - log slow operations (by default, >100ms is considered slow)
• 2 - log all operations
> db.setProfilingLevel(2);
29. Schema Design
Some tips
1. Duplicate data for speed, reference data for integrity
2. Try to fetch data in a single query
3. Design documents to be self-sufficient
4. Override _id when you have your own simple, unique id
5. Don’t always use an index
30. Schema Design
Conclusion
• Embedded docs are good for fast queries
• Embedded and nested docs are good for storing hierarchies
• Normalized docs are a most acceptable