定义
语法
hasRoot 通过以下语法实现:
{ $search: { "index": "<index name>", // optional, defaults to "default" "hasRoot": { "operator": { <operator-specification> } }, "returnScope": { "path": "<embedded-documents-field-to-retrieve>" }, "returnStoredSource": true, }}字段
字段 | 类型 | 说明 | 必要性 |
|---|---|---|---|
| 对象 | 用于查询索引字段的操作符。这指定了用于过滤子文档的搜索条件。 | 必需 |
要求
要使用此操作符,您必须在索引定义中执行以下操作:
索引您要查询的根级字段。
将要检索的对象数组索引为
embeddedDocuments类型。您还必须为要检索的嵌套字段配置storedSource。
在查询中,您必须执行以下操作:
指定
returnScope以设置搜索操作符的字段范围。将
returnStoredSource设置为true以返回storedSource字段。
示例
本节中的示例使用 sample_training.companies 命名空间。如果您加载了示例数据集并在集合上创建索引,则可以尝试本节中演示的示例查询。
样本索引
本节中的查询使用以下索引。此索引定义将 MongoDB Search 配置为执行以下操作:
自动索引集合中所有可动态索引的字段。
将
products、funding_rounds和funding_rounds.investments字段索引为 embeddedDocuments 类型。将以下字段存储在
mongot上:funding_rounds.raised_currency_codefunding_rounds.raised_amountfunding_rounds.investmentsproducts.name
{ "mappings": { "dynamic": true, "fields": { "funding_rounds": { "dynamic": true, "fields": { "investments": [ { "dynamic": true, "type": "embeddedDocuments" } ] }, "storedSource": { "include": [ "raised_currency_code", "raised_amount", "investments" ] }, "type": "embeddedDocuments" }, "products": { "dynamic": true, "storedSource": { "include": [ "name" ] }, "type": "embeddedDocuments" } } }}简单查询
以下查询返回 products,其中根级字段 founded_year 在 2005 和 2010 年之间。
db.companies.aggregate([ { "$search": { "returnStoredSource": true, "returnScope": { "path": "products" }, "hasRoot": { "operator": { "range": { "path": "founded_year", "gte": 2005, "lte": 2010 } } } } }])多级查询
以下查询使用 text 操作符在 name 字段中搜索名为 Facebook 的公司,以检索公司所有投资者(investments.person和investments.financial_org)的投资金额(funding_rounds.raised_amount和funding_rounds.raised_currency_code)。
db.companies.aggregate([ { "$search": { "returnStoredSource": true, "returnScope": { "path": "funding_rounds" }, "hasRoot": { "operator": { "text": { "path": "name", "query": "Facebook" } } } } }])复合查询
以下查询在嵌套的 funding_rounds.investments 字段中搜索包含术语 Ventures(在 name 字段中的任何位置)的金融组织,这些组织已投资于使用术语 network(在 description 字段中的任何位置)描述的公司。该查询使用复合操作符来搜索:
使用
embeddedDocument操作符的嵌套funding_rounds.investments.financial_org.name字段使用
hasRoot操作符的根级description字段
returnScope 为操作符设置上下文到 funding_rounds embeddedDocuments 类型字段,并将 returnStoredSource 字段设置为 true 以仅返回 storedSource 字段。该查询将结果限制为 5 个文档。
db.companies.aggregate([ { "$search": { "compound": { "should": [ { "embeddedDocument": { "path": "funding_rounds.investments", "operator": { "wildcard": { "path": "funding_rounds.investments.financial_org.name", "query": "*Ventures*", "allowAnalyzedField": true } } } }, { "hasRoot": { "operator": { "wildcard": { "path": "description", "query": "*network*", "allowAnalyzedField": true } } } } ] }, "returnScope": {"path": "funding_rounds"}, "returnStoredSource": true } }, { "$limit": 5 }])