Docs 菜单
Docs 主页
/ /

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

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

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

  • 将对象数组索引为 embeddedDocuments 类型。

  • 为要检索的嵌套字段定义 storedSource。MongoDB 搜索仅返回在 storedSource 中定义的字段。

  • 在查询中将 returnStoredSource 选项设置为 true

returnScope 查询中包含以下语法:

{
$search: {
"<operator>": {
<operator-specification>,
},
"returnScope": {
"path": "<embedded-documents-field-to-retrieve>"
},
"returnStoredSource": true
}
}
{
$searchMeta: {
"returnScope": {
"path": "<embedded-documents-field-to-retrieve>"
},
"returnStoredSource": true
},
"facet": {
"<operator>": {
<operator-specification>,
},
"facets": {
<facet-definition>
}
}
}

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

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

在您的操作符规范中,您必须指定要查询的字段的完整路径。

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

以下示例演示了如何在查询中使用 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_roundsfunding_rounds.investments 字段作为 embeddedDocuments 类型进行索引。

  • 为嵌套在 funding_roundsfunding_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_roundsfunding_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 类型字段的示例查询。

后退

searchSequenceToken

在此页面上