Database Manual / Data Modeling / Schema Design Patterns

Polymorphic Data多态数据

MongoDB uses a flexible data model, which means documents in a single collection do not need to have the same structure. Polymorphic data is data in a single collection that varies in document fields or data types.MongoDB使用灵活的数据模型,这意味着单个集合中的文档不需要具有相同的结构。多态数据是指单个集合中的数据,其文档字段或数据类型各不相同。

Generally, documents in a collection are similar in structure but may contain slight variations depending on the application. 一般来说,集合中的文档在结构上是相似的,但根据应用程序的不同,可能会包含轻微的变化。To group similar, non-identical documents in a single collection you can use the Polymorphic and the Inheritance schema design patterns.要将相似、不相同的文档分组到单个集合中,可以使用多态继承模式设计模式。

These schema designs can improve performance by storing data based on query access patterns, rather than storing data strictly based on document shape.这些模式设计可以通过基于查询访问模式存储数据来提高性能,而不是严格基于文档形状存储数据。

Use Cases用例

Scenario场景Design Pattern Application设计模式应用
Your application tracks professional athletes across different sports. Your queries access all athletes, but the attributes stored for each athlete vary depending on their sport.应用程序跟踪不同运动的职业运动员。查询可以访问所有运动员,但为每个运动员存储的属性因运动而异。Use the polymorphic pattern to group athletes in a single collection. Even though the documents have different shapes, they can still be accessed with a single query.使用多态模式将运动员分组到一个集合中。尽管文档具有不同的形状,但仍然可以通过单个查询访问它们。
Your application tracks books in a bookstore. Books can be available in different forms: ebook, print, or audiobook. All books share the fields of title, author, and genre but have additional differing fields depending on their format.应用程序跟踪书店中的书籍。书籍可以以不同的形式提供:电子书、印刷品或有声读物。所有书籍共享titleauthorgenre字段,但根据其格式,还有其他不同的字段。Use the inheritance pattern to group books into a single collection. Each book format is a child entity of the parent entity of book that provides the shared fields of title, author, and genre across all formats. 使用继承模式将书籍分组到一个集合中。每种图书格式都是book父实体的子实体,父实体提供所有格式的titleauthorgenre等共享字段。Despite the additional differing fields of the child entities, the shared fields from the parent entity allow them to be grouped into a single collection.尽管子实体有其他不同的字段,但父实体的共享字段允许将它们分组到单个集合中。

Get Started开始使用

Learn More了解更多