Database Manual / Data Modeling

Database References数据库参考

For many use cases in MongoDB, the denormalized data model where related data is stored within a single document is optimal. However, in some cases, it makes sense to store related information in separate documents, typically in different collections or databases.对于MongoDB中的许多用例,将相关数据存储在单个文档中的非规范化数据模型是最佳选择。然而,在某些情况下,将相关信息存储在单独的文档中是有意义的,通常是在不同的集合或数据库中。

Important

You can use the $lookup pipeline stage to perform a left outer join to an unsharded collection in the same database.您可以使用$lookup管道阶段对同一数据库中的未记录集合执行左外连接。

You can also use the $graphLookup pipeline stage to join an unsharded collection to perform recursive search.您还可以使用$graphLookup管道阶段加入未记录的集合以执行递归搜索。

This page outlines alternative procedures that predate the $lookup and $graphLookup pipeline stages.本页概述了$lookup$graphLookup管道阶段之前的替代过程。

You can create a database reference for deployments hosted in the following environments:您可以为在以下环境中托管的部署创建数据库引用:

MongoDB applications use one of two methods to relate documents:MongoDB应用程序使用以下两种方法之一来关联文档:

To resolve DBRefs, your application must perform additional queries to return the referenced documents. Some MongoDB drivers provide helper methods to enable DBRefs to be resolved into documents, but it doesn't happen automatically.要解析DBRef,应用程序必须执行其他查询以返回引用的文档。一些MongoDB驱动程序提供了帮助方法,使DBRef能够解析为文档,但它不会自动发生。

DBRefs provide a common format and type to represent relationships among documents. The DBRef format also provides common semantics for representing links between documents if your database must interact with multiple frameworks and tools.DBRef提供了一种通用的格式和类型来表示文档之间的关系。如果数据库必须与多个框架和工具交互,DBRef格式还提供了表示文档之间链接的通用语义。

Unless you have a compelling reason to use DBRefs, use manual references instead.除非您有令人信服的理由使用DBRefs,否则请使用手动引用。

Manual References手册参考

Background背景

A manual reference is the practice of including one document's _id field in another document. The application can then issue a second query to resolve the referenced fields as needed.手动参考是将一个文档_id字段包含在另一个文档中的做法。然后,应用程序可以根据需要发出第二个查询来解析引用的字段。

Create a Manual Reference in the MongoDB Atlas UI在MongoDB Atlas UI中创建手册参考

To create a manual reference in the MongoDB Atlas UI, follow these steps:要在MongoDB Atlas UI中创建手动参考,请执行以下步骤:

1

In the MongoDB Atlas UI, go to the Clusters page for your project.在MongoDB Atlas UI中,转到项目的“集群”页面。

Warning

Navigation Improvements In Progress导航改进正在进行中

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview Atlas documentation.我们目前正在推出一种新的、改进的导航体验。如果以下步骤与Atlas UI中的视图不匹配,请参阅Atlas预览文档

  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.如果尚未显示,请从导航栏的“组织”菜单中选择包含所需项目的组织。
  2. If it's not already displayed, select your project from the Projects menu in the navigation bar.如果尚未显示,请从导航栏中的“项目”菜单中选择项目。
  3. If it's not already displayed, click Clusters in the sidebar.如果尚未显示,请单击侧栏中的“集群”。

    The Clusters page displays.将显示“群集”页面。

2

Navigate to the collection.导航到集合。

  1. For the cluster where you want to add a database reference, click Browse Collections.对于要添加数据库引用的集群,单击“浏览集合”。
  2. In the left navigation pane, select the database.在左侧导航窗格中,选择数据库。
  3. In the left navigation pane, select the collection. This example references a places collection.在左侧导航窗格中,选择集合。此示例引用了一个places集合。
3

Add a document.添加文档。

  1. Click Insert Document.单击“插入文档”。
  2. Click the JSON view icon ({{}}).单击JSON视图图标({{}})。
  3. Paste the following data into the document:将以下数据粘贴到文档中:

    {
    "_id": {
    "$oid": "651aea5870299b120736f442"
    },
    "name": "Broadway Center",
    "url": "bc.example.net"
    }
  4. Click Insert.单击“插入”。
4

Add a document in the people collection that references the entry in places.people集合中添加一个文档,在某些places引用该条目。

  1. In the left navigation pane, select a different collection. This example references a people collection.在左侧导航窗格中,选择其他集合。此示例引用了一个people集合。
  2. Click Insert Document.单击“插入文档”。
  3. Click the JSON view icon ({{}}).单击JSON视图图标({{}})。
  4. Paste the following data into the document:将以下数据粘贴到文档中:

    {
    "_id": {
    "$oid": "651aebeb70299b120736f443"
    },
    "name": "Erin",
    "places_id": "651aea5870299b120736f442"
    "url": "bc.example.net/Erin"
    }
  5. Click Insert.单击“插入”。

    When a query returns the document from the people collection you can, if needed, filter the query results from the places collection for the document referenced by the places_id field.当查询从people集合返回文档时,如果需要,您可以从places_id字段引用的文档的places集合中筛选查询结果。

    To learn more about running queries in MongoDB Atlas, see View, Filter, and Sort Documents in the MongoDB Atlas documentation.要了解有关在MongoDB Atlas中运行查询的更多信息,请参阅MongoDB Atlas文档中的查看、筛选和排序文档

Create a Manual Reference in the Terminal在终端中创建手动参考

Consider the following operation to insert two documents, using the _id field of the first document as a reference in the second document:考虑以下操作来插入两个文档,使用第一个文档的_id字段作为第二个文档中的引用:

original_id = ObjectId()

db.places.insertOne({
"_id": original_id,
"name": "Broadway Center",
"url": "bc.example.net"
})

db.people.insertOne({
"name": "Erin",
"places_id": original_id,
"url": "bc.example.net/Erin"
})

Then, when a query returns the document from the people collection you can, if needed, make a second query for the document referenced by the places_id field in the places collection.然后,当查询从people集合返回文档时,如果需要,您可以对places集合中places_id字段引用的文档进行第二次查询。

Use使用

For nearly every case where you want to store a relationship between two documents, use manual references. The references are simple to create and your application can resolve references as needed.对于几乎所有想要存储两个文档之间关系的情况,请使用手动引用。创建引用很简单,应用程序可以根据需要解析引用。

The only limitation of manual linking is that these references do not convey the database and collection names. If you have documents in a single collection that relate to documents in more than one collection, you may need to consider using DBRefs.手动链接的唯一限制是这些引用不传达数据库和集合名称。如果单个集合中的文档与多个集合中的文件相关,则可能需要考虑使用DBRefs。

DBRefs

Background背景

DBRefs are a convention for representing a document, rather than a specific reference type. They include the name of the collection, and in some cases the database name, in addition to the value from the _id field.DBRef是一种表示文档的约定,而不是特定的引用类型。除了_id字段中的值外,它们还包括集合的名称,在某些情况下还包括数据库名称。

Optionally, DBRefs can include any number of other fields. Extra field names must follow any rules for field names imposed by the server version.DBRef可以视需要包含任意数量的其他字段。额外的字段名必须遵循服务器版本强加的字段名规则。

Format格式

DBRefs have the following fields:DBRef具有以下字段:

$ref
The $ref field holds the name of the collection where the referenced document resides.$ref字段保存引用文档所在的集合的名称。
$id
The $id field contains the value of the _id field in the referenced document.$id字段包含引用文档中_id字段的值。
$db

Optional.

Contains the name of the database where the referenced document resides.包含引用文档所在的数据库的名称。

Example示例

DBRef documents resemble the following document:DBRef文档类似于以下文档:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

Consider a document from a collection that stored a DBRef in a creator field:考虑一个来自集合的文档,该文档在creator字段中存储了DBRef:

{
"_id" : ObjectId("5126bbf64aed4daf9e2ab771"),
// .. application fields
"creator" : {
"$ref" : "creators",
"$id" : ObjectId("5126bc054aed4daf9e2ab772"),
"$db" : "users",
"extraField" : "anything"
}
}

The DBRef in this example points to a document in the creators collection of the users database that has ObjectId("5126bc054aed4daf9e2ab772") in its _id field. It also contains an optional field.此示例中的DBRef指向users数据库creators集合中的一个文档,该文档的_id字段中有ObjectId("5126bc054aed4daf9e2ab772")。它还包含一个可选字段。

Note

The order of fields in the DBRef matters, and you must use the above sequence when using a DBRef.DBRef中字段的顺序很重要,使用DBRef时必须使用上述顺序。

Driver Support for DBRefsDBRefs的驱动程序支持

Driver驱动程序DBRef Support支持Notes备注
CNot Supported不支持You can traverse references manually.您可以手动遍历引用。
C++Not Supported不支持You can traverse references manually.您可以手动遍历引用。
C#Supported支持Please see the C# driver page for more information.有关更多信息,请参阅C#驱动程序页面。
GoNot Supported不支持You can traverse references manually.您可以手动遍历引用。
HaskellNot Supported不支持You can traverse references manually.您可以手动遍历引用。
JavaSupported支持Please see the Java driver page for more information.有关更多信息,请参阅Java驱动程序页面
Node.jsSupported支持Please see the Node.js driver page for more information.请参阅Node.js驱动程序页面以获取更多信息。
PerlSupported支持Please see the Perl driver page for more information.有关更多信息,请参阅Perl驱动程序页面
PHPNot Supported不支持You can traverse references manually.您可以手动遍历引用。
PythonSupported支持Please see the PyMongo driver page for more information.请参阅PyMongo驱动程序页面以获取更多信息。
RubySupported支持Please see the Ruby driver page for more information.请参阅Ruby驱动程序页面以获取更多信息。
ScalaNot Supported不支持You can traverse references manually.您可以手动遍历引用。

Use使用

In most cases you should use the manual reference method for connecting two or more related documents. However, if you need to reference documents from multiple collections, consider using DBRefs.在大多数情况下,您应该使用手动引用方法来连接两个或多个相关文档。但是,如果需要引用多个集合中的文档,请考虑使用DBRefs。