使用文档引用建立一对多关系模型
Overview
本页描述了一种数据模型,该模型使用文档之间的引用来描述连接数据之间的一对多关系。
模式
以下示例展示如何映射出版商和图书关系。该示例说明在避免出版商信息冗余方面,引用比嵌入更有优势。
将出版商文档嵌入图书文档会导致出版商数据重复,如以下文档所示:
{ title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English", publisher: { name: "O'Reilly Media", founded: 1980, location: "CA" } } { title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English", publisher: { name: "O'Reilly Media", founded: 1980, location: "CA" } }
为避免出现重复的出版商数据,请使用引用并将出版商信息保存在图书集合之外的单独集合中。
使用引用时,关系的增长将决定引用的存储方式。如果每个出版商的图书数量较少且增长有限,则将图书引用存储在出版商文档中有时可能十分有用。相反,当每个出版商的图书数量没有限制时,此数据模型将导致可变且不断增长的数组,如以下示例所示:
{ name: "O'Reilly Media", founded: 1980, location: "CA", books: [123456789, 234567890, ...] } { _id: 123456789, title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English" } { _id: 234567890, title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English" }
为避免出现可变且不断增长的数组,请将出版商的引用存储在图书文档中:
{ _id: "oreilly", name: "O'Reilly Media", founded: 1980, location: "CA" } { _id: 123456789, title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English", publisher_id: "oreilly" } { _id: 234567890, title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English", publisher_id: "oreilly" }