存在
定义
exists
exists
操作符会测试指定已索引字段名称的路径在文档中是否存在。如果指定的字段存在但未进行索引,则不会将文档包含在结果集中。exists
通常作为 复合查询的一部分与其他搜索子句一起使用。
语法
exists
通过以下语法实现:
1 { 2 $search: { 3 "index": <index name>, // optional, defaults to "default" 4 "exists": { 5 "path": "<field-to-test-for>", 6 "score": <options> 7 } 8 } 9 }
选项
exists
使用以下词条来构造查询:
字段 | 类型 | 说明 | 必需? |
---|---|---|---|
| 字符串 | 要搜索的索引字段。 | 是 |
| 对象 | 分配给匹配搜索结果的分数。要详细了解修改默认分数的选项,请参阅对结果中的文档进行评分。 | no |
评分行为
Atlas Search 为结果集中的所有文档分配 constant
分数 1
。您可以使用 score
选项自定义默认 Atlas Search 分数。要详细了解如何修改 Atlas Search 返回的默认分数,请参阅修改分数。
示例
您可以在 Atlas Search Playground 或 Atlas 集群中尝试以下示例。
样本集合
本页上的示例使用名为 fruit
的集合,其中包含以下文档:
1 { 2 "_id" : 1, 3 "type" : "apple", 4 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp." 5 }, 6 { 7 "_id" : 2, 8 "type" : "banana", 9 "description" : "Bananas are usually sold in bunches of five or six." 10 }, 11 { "_id" : 3, 12 "type": "apple", 13 "description" : "Apple pie and apple cobbler are popular apple-based desserts." 14 }, 15 { "_id" : 4, 16 "description" : "Types of citrus fruit include lemons, oranges, and grapefruit.", 17 "quantities" : { 18 "lemons": 200, 19 "oranges": 240, 20 "grapefruit": 160 21 } 22 }
样本索引
fruit
集合有一个使用默认 标准分析器的默认动态 Atlas Search 索引。standard
分析器将所有单词转为小写并忽略常见的非索引字("the", "a", "and",
等)。
样本查询
以下查询演示了 Atlas Search 查询中的 exists
操作符。
基本示例
以下示例搜索包含名为 type
的字段的文档。
1 db.fruit.aggregate([ 2 { 3 $search: { 4 "exists": { 5 "path": "type" 6 } 7 } 8 } 9 ])
上面的查询返回集合的前三个文档。不包括具有 _id: 4
的文档,因为它没有 type
字段。
嵌入式示例
使用点符号搜索嵌入式字段。以下示例搜索在名为 quantities
的字段中嵌入了名为 lemons
的字段的文档。
1 db.fruit.aggregate([ 2 { 3 "$search": { 4 "exists": { 5 "path": "quantities.lemons" 6 } 7 } 8 } 9 ])
1 { 2 "_id" : 4, 3 "description" : "Types of citrus fruit include lemons, oranges, and grapefruit.", 4 "quantities" : { 5 "lemons": 200, 6 "oranges": 240, 7 "grapefruit": 160 8 } 9 }
➤ 尝试 Atlas Search Playground 中的示例。
复合示例
以下示例将 exists
作为复合查询的一部分。
1 db.fruit.aggregate([ 2 { 3 $search: { 4 "compound": { 5 "must": [ 6 { 7 "exists": { 8 "path": "type" 9 } 10 }, 11 { 12 "text": { 13 "query": "apple", 14 "path": "type" 15 } 16 }], 17 "should": { 18 "text": { 19 "query": "fuji", 20 "path": "description" 21 } 22 } 23 } 24 } 25 } 26 ])
1 { 2 "_id" : 1, 3 "type" : "apple", 4 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp." 5 } 6 { 7 "_id" : 3, 8 "type" : "apple", 9 "description" : "Apple pie and apple cobbler are popular apple-based desserts." 10 }
两个文档都具有 type
字段,并且都包含搜索词语 apple
。先返回包含 _id: 1
的文档,因为它满足 should
子句的要求。
➤ 尝试 Atlas Search Playground 中的示例。