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