DEV Community

Cover image for 💡技巧和诀窍:MongoDB多态性和异常值模式 💡
Danny Chan for MongoDB Builders

Posted on

2 2 2 2 2

💡技巧和诀窍:MongoDB多态性和异常值模式 💡

🔍 扩展性:

  • 成本更低
  • 通过分片实现水平扩展的灵活性
  • 将数据分布在多台服务器上
  • 当数据库容量超出时,可进行分片并分散到两台服务器


🔍 BSON:

  • JSON(JavaScript对象表示法)文档的二进制表示
  • 数据类型: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


🗄️ 文档:

  • 被分组存储在集合中
  • 16兆字节大小限制
  • 相关的集合会被分组存储在一个数据库中


🔑 _id:

  • 每个集合中的文档都有唯一的_id
  • 不可变
  • 可以是任何类型(不能是数组)


🤯 挑战:

  • 应该一起访问的数据应该被存储在一起
  • 存储成本很小,开发人员成本很高
  • 不要为存储优化,而要为开发人员的生产力和查询优化而优化
  • 实现业务逻辑
  • 优化数据模型以提高开发人员的生产力和查询优化


🔍 验证选项:

  • 可以选择在违反验证规则时抛出错误或警告


🤟 拥抱文档多样性:

  • 同一集合中的文档并不需要具有相同的字段


🤖 多态模式:

  • 集合中的文档类似但不完全相同
  • 根据查询需求将文档分组
  • 示例:
{
    "type": "singles",
    "titles": 167
}
{
    "type": "doubles",
    "titles": 177,
    "tournaments": 233
}
Enter fullscreen mode Exit fullscreen mode


🤯 异常值模式:

  • 解决异常值用例(文档中包含数百万个嵌入数据)
  • 添加has_extras字段
  • 创建一个新文档来存储其他嵌入数据
  • 示例:
{
    "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

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay