On this page本页内容
This page describes a data model that uses references between documents to describe one-to-many relationships between connected data.本页描述了一个数据模型,该模型使用文档之间的引用来描述连接数据之间的一对多关系。
Consider the following example that maps publisher and book relationships. 考虑以下映射出版商和图书关系的示例。The example illustrates the advantage of referencing over embedding to avoid repetition of the publisher information.该示例说明了引用优于嵌入的优点,以避免发布者信息的重复。
Embedding the publisher document inside the book document would lead to repetition of the publisher data, as the following documents show:将publisher文档嵌入图书文档将导致publisher
数据的重复,如下文档所示:
{ 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" } }
To avoid repetition of the publisher data, use references and keep the publisher information in a separate collection from the book collection.为了避免出版商数据的重复,请使用引用,并将出版商信息保存在与图书集合不同的集合中。
When using references, the growth of the relationships determine where to store the reference. 使用引用时,关系的增长决定了将引用存储在何处。If the number of books per publisher is small with limited growth, storing the book reference inside the publisher document may sometimes be useful. 如果每个出版商的图书数量很少且增长有限,那么将图书参考存储在出版商文档中有时可能很有用。Otherwise, if the number of books per publisher is unbounded, this data model would lead to mutable, growing arrays, as in the following example:否则,如果每个出版商的图书数量是无限的,则此数据模型将导致可变的、不断增长的数组,如以下示例所示:
{ 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" }
To avoid mutable, growing arrays, store the publisher reference inside the book document:为了避免可变的、不断增长的数组,请将publisher引用存储在book文档中:
{ _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" }