Model One-to-Many Relationships with Document References建立与文档引用的一对多关系模型
On this page本页内容
Overview概述
This page describes a data model that uses references between documents to describe one-to-many relationships between connected data.此页面描述了一个数据模型,该模型使用文档之间的引用来描述连接数据之间的一对多关系。
Pattern模式
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:如以下文档所示,将出版商文档嵌入图书文档将导致出版商数据的重复:
{
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:为了避免可变的、不断增长的数组,请将发布者引用存储在图书文档中:
{
_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"
}