对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

查询筛选条件、和检索对象数组

您可以使用 returnScope 选项设立查询上下文,并将对象数组作为单个文档返回。

要使用 returnScope 将嵌套对象作为独立文档检索,您必须:

returnScope 查询中包含以下语法:

要了解有关查询语法的更多信息,请参阅$search 。

returnScope 选项设置查询的检索上下文。如果您在查询中指定 returnScope,MongoDB Search 就会像处理单个文档一样对每个嵌入式文档进行评分、排序和计数。

当您使用 returnScope 选项时,MongoDB Search 仅返回您在 embeddedDocument 中配置为 storedSource 的字段。embeddedDocument 路径之外的字段(例如根级字段)和未配置为 storedSource 的字段不会被返回。

在操作符规范中,必须指定要查询的字段的完整路径。使用 returnScope 选项时,必须确保所有操作符规范路径都嵌套在 returnScope.path 下。要查询returnScope.path 之外的字段,必须使用 hasAncestor 或 hasRoot操作符。要学习;了解详情,请参阅:

在查询中使用 returnScope 时,MongoDB Search 会填充 searchRootDocumentId 元数据字段。您可以在运行 MongoDB 8.3 或更高版本的集群上使用 searchRootDocumentId 元数据字段。此字段包含每个返回的嵌入式文档所在的根文档的标识符。要预计此值,请将 $meta 表达式与 searchRootDocumentId 关键字一起使用。

MongoDB Search 仅当您的查询同时设置 returnStoredSource: true 和 returnScope.path 时才填充 searchRootDocumentId。如果您在查询中引用 searchRootDocumentId,但查询未指定 returnScope,则查询将失败并显示以下错误:

query requires $search root document id metadata, but it is not
available

如果您想进行以下操作,请使用 searchRootDocumentId:

  • 在对子文档进行过滤后,从父文档中获取字段。

  • 按父文档对子文档进行分组。

如果出现以下情况,请勿使用 searchRootDocumentId:

  • 您只需要匹配的子文档中的字段。

  • 您希望返回结果集中每个子文档的父文档,因为这可能会很耗时。

以下示例演示了如何在查询中使用 returnScope 选项。这些示例使用 sample_training.companies 示例数据集。如果您在集群上加载数据并在集合的字段上创建示例索引,则可以针对示例数据运行以下查询。

1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "funding_rounds": {
6 "type": "embeddedDocuments",
7 "dynamic": true,
8 "fields": {
9 "investments": {
10 "type": "embeddedDocuments",
11 "dynamic": true
12 }
13 },
14 "storedSource": {
15 "include": [
16 "round_code",
17 "raised_currency_code",
18 "raised_amount",
19 "investments.person",
20 "investments.financial_org"
21 ]
22 }
23 }
24 }
25 }
26}

前面的索引定义将MongoDB 搜索配置为:

  • 将 funding_rounds 和 funding_rounds.investments 字段作为 embeddedDocuments 类型进行索引。

  • 为嵌套在 funding_rounds 和 funding_rounds.investments 对象数组中的所有可动态索引的字段建立索引。

  • 将以下字段存储在 mongot 上:

    • funding_rounds.round_code

    • funding_rounds.raised_currency_code

    • funding_rounds.raised_amount

    • funding_rounds.investments.person

    • funding_rounds.investments.financial_org

您可以使用embeddedDocument 操作符对 funding_rounds 和 funding_rounds.investments 字段进行逐元素查询。以下章节展示了一些使用 returnScope 选项将 embeddedDocuments 字段作为单独文档检索的示例查询。

来自 sample_training.companies 集合的示例文档结构
{
...,
"funding_rounds": [
{
"id": <integer>,
"round_code": "<string>",
"source_url": "<string>",
"source_description": "<string>",
"raised_amount": <integer>,
"raised_currency_code": "<string>",
"funded_year": <integer>,
"funded_month": "<string>",
"funded_day": "<string>",
"investments": [
{
"company": "<string>",
"financial_org": {
"name": "<string>",
"permalink": "<string>"
},
"person": {
"first_name": "<string>",
"last_name": "<string>",
"permalink": "<string>"
}
},
...
]
},
...
],
...
}

以下各节演示了使用 returnScope 选项检索存储在 mongot 上的 embeddedDocuments 类型字段的示例查询。