DEV Community

Cover image for πŸ’‘ Tip and Trick: MongoDB Polymorphic & Outlier Pattern πŸ’‘
Danny Chan for MongoDB Builders

Posted on

πŸ’‘ Tip and Trick: MongoDB Polymorphic & Outlier Pattern πŸ’‘

πŸ” Scale:

  • Cheaper
  • Flexibility to scale horizontally through sharding
  • Distributing data across multiple servers
  • When database exceeds capacity, sharding and split it over two servers


πŸ” BSON:

  • Binary representation of JSON (JavaScript Object Notation) documents
  • Data types: Double, String, Object, Array, Binary Data, ObjectId, Boolean, Date, Null, Regular Expression, JavaScript, 32-bit Integer, Timestamp, 64-bit Integer, Decimal128, Min Key, Max Key


πŸ—„οΈ Documents:

  • Grouped together in collections
  • 16 megabyte size limit
  • Related collections are grouped together and stored in a database


πŸ”‘ _id:

  • Unique for each document in a collection
  • Immutable
  • Any type (cannot be array)


🀯 Challenge:

  • Access data together should be stored together
  • Storage is a small cost, developers are expensive
  • Instead of optimizing for storage, optimize for developers' time
  • Implementing business logic
  • Optimize data model for developer productivity and query optimization


πŸ” Validation Option:

  • Choice of throwing an error or a warning if a validation rule is violated


🀟 Embrace Document Diversity:

  • Not all documents in a collection need to have the same fields


πŸ€– Polymorphic Pattern:

  • Collections are of similar, but not identical
  • Grouping documents together based on the queries
  • Example:
{
    "type": "singles",
    "titles": 167
}
{
    "type": "doubles",
    "titles": 177,
    "tournaments": 233
}
Enter fullscreen mode Exit fullscreen mode


🀯 Outlier Pattern:

  • Solve outlier use case (a document has millions of embedding data)
  • Add has_extras fields
  • Create a new document where store other embedding data
  • Example:
{
    "author": "Ken W. Alger",
    "customers_purchased": ["user00", "user01"]
}
{
   "author": "J.K. Rowling",
   "customers_purchased": ["user00", ..., "user999"],
   "has_extras": "true"
}
Enter fullscreen mode Exit fullscreen mode


🀯 Reference:

https://www.mongodb.com/developer/products/mongodb/polymorphic-pattern/
Building with Patterns: The Polymorphic Pattern

https://www.mongodb.com/blog/post/building-with-patterns-the-outlier-pattern
Building With Patterns: The Outlier Pattern


Editor

Image description

Danny Chan, specialty of FSI and Serverless

Image description

Kenny Chan, specialty of FSI and Machine Learning

Top comments (0)