文档菜单
文档首页
/
MongoDB 手册
/ / /

使用继承模式

本页内容

  • 关于此任务
  • 步骤
  • 了解更多

当您的文档大多相似且希望将它们保存在同一集合中以便一起阅读时,请使用继承模式。继承模式使用具有共同字段的父实体来分组具有不同形式的子实体。子实体可以具有唯一的字段,但它们由于共同的字段而紧密相关。

在此示例中,一家书店使用继承模式来存储不同类型的媒体。book 父实体存储如 titleauthor 的常见字段,并且多个子实体从 book 实体继承。例如,有声书、平装书和电子书具有共同字段,同时也具有特定于媒体类型的唯一字段。

继承模式将这些略有不同的实体存储在同一集合中,从而提高了需要访问所有书籍(无论类型如何)的查询的性能。

1
db.books.insertMany( [
{
product_type: "ebook",
title: "Practical MongoDB Aggregations",
author: "Paul Done",
rating: 4.8,
genres: [ "programming" ],
pages: 338,
download_url: "<url>"
},
{
product_type: "audiobook",
title: "Practical MongoDB Aggregations",
author: "Paul Done",
rating: 4.6,
genres: [ "programming" ],
narrators: [ "Paul Done" ],
duration: {
hours: 21,
minutes: 8
},
time_by_chapter: [
{
chapter: 1,
start: "00:00:00",
end: "01:00:00"
},
{
chapter: 2,
start: "01:00:00",
end: "01:55:00"
}
]
},
{
product_type: "physical_book",
title: "Practical MongoDB Aggregations",
author: "Paul Done",
rating: 4.9,
genres: [ "programming" ],
pages: 338,
stock: 12,
delivery_time: 2
}
] )

前面的文档共享一些共同字段,并且根据 product_type 有独特的字段。例如

  • 电子书 文档有一个 download_url 字段。

  • 有声书 文档有一个 time_by_chapter 字段。

  • 实物书 文档有一个 delivery_time 字段。

2

尽管 books 集合中的文档形状不同,但您可以使用单个查询返回所有文档

db.books.find()

输出

[
{
_id: ObjectId('66eb4160ef006be6eda8e2ee'),
product_type: 'ebook',
title: 'Practical MongoDB Aggregations',
author: 'Paul Done',
rating: 4.8,
genres: [ 'programming' ],
pages: 338,
download_url: '<url>'
},
{
_id: ObjectId('66eb4160ef006be6eda8e2ef'),
product_type: 'audiobook',
title: 'Practical MongoDB Aggregations',
author: 'Paul Done',
rating: 4.6,
genres: [ 'programming' ],
narrators: [ 'Paul Done' ],
duration: { hours: 21, minutes: 8 },
time_by_chapter: [
{ chapter: 1, start: '00:00:00', end: '01:00:00' },
{ chapter: 2, start: '01:00:00', end: '01:55:00' }
]
},
{
_id: ObjectId('66eb4160ef006be6eda8e2f0'),
product_type: 'physical_book',
title: 'Practical MongoDB Aggregations',
author: 'Paul Done',
rating: 4.9,
genres: [ 'programming' ],
pages: 338,
stock: 132,
delivery_time: 2
}
]
3

继承模式不需要额外的逻辑来查询特定媒体类型的字段。例如,以下查询返回持续时间超过20小时的书,这仅适用于产品类型 audio_book

db.books.find(
{
"duration.hours": { $gt: 20 }
}
)

输出

[
{
_id: ObjectId('66eb4160ef006be6eda8e2ef'),
product_type: 'audiobook',
title: 'Practical MongoDB Aggregations',
author: 'Paul Done',
rating: 4.6,
genres: [ 'programming' ],
narrators: [ 'Paul Done' ],
duration: { hours: 21, minutes: 8 },
time_by_chapter: [
{ chapter: 1, start: '00:00:00', end: '01:00:00' },
{ chapter: 2, start: '01:00:00', end: '01:55:00' }
]
}
]
  • 存储多态数据

  • 模式验证

  • 创建索引以支持您的查询

返回

多态模式