对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

使用继承模式

当您的文档非常相似并且您希望将它们保留在同一个集合中以便一起阅读时,请使用继承模式。 继承模式使用具有公共字段的父实体对具有可变形式的子实体进行群组。 子实体可以具有唯一字段,但由于其公共字段而彼此密切相关。

在此示例中,一家存储使用继承模式来存储不同类型的媒体。 book 父实体存储 title 和 author 等常用字段,多个子实体从 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 。示例:

  • ebook 文档具有 download_url字段。

  • audiobook 文档具有 time_by_chapter字段。

  • physical_book 文档具有 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' } ] }]
获得技能徽章

免费掌握“模式设计模式和反模式”!

了解详情

给本页内容打分