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

使用文档引用建立一对一关系

本页内容

  • 概述
  • 模式

本页面描述了一个使用引用的数据库模型,用于描述连接数据之间的一对多关系。

考虑以下示例,该示例映射了出版商和书籍之间的关系。该示例说明了引用相对于嵌入的优点,可以避免重复出版商信息。

将出版商文档嵌入到书籍文档中会导致出版商数据的重复,如下面的文档所示

{
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"
}

返回

一对多嵌入文档

本页内容