Docs 菜单
Docs 主页
/ /

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

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

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

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

  • 为要检索的嵌套字段定义 StoredSource。 MongoDB Search 仅返回 中定义的字段。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搜索会对每个嵌入式文档进行评分、排序和计数,就像它是单个文档一样。

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

当您使用 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 Search 配置为:

  • 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

在此页面上