“文档” 菜单
文档首页
/
MongoDB 阿特拉斯
/ / / /

存在

在此页面上

  • 定义
  • 语法
  • 选项
  • 评分行为
  • 举例
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 使用以下词条来构造查询:

字段
类型
说明
必需?
path
字符串
要搜索的索引字段。
score
对象
分配给匹配搜索结果的分数。要详细了解修改默认分数的选项,请参阅对结果中的文档进行评分
没有

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 的字段的文档。

1db.fruit.aggregate([
2 {
3 $search: {
4 "exists": {
5 "path": "type"
6 }
7 }
8 }
9])

上面的查询返回集合的前三个文档。不包括具有 _id: 4 的文档,因为它没有 type 字段。

➤ 在 Atlas Search Playground 中尝试此操作。

使用点符号搜索嵌入式字段。以下示例搜索在名为 quantities 的字段中嵌入了名为 lemons 的字段的文档。

1db.fruit.aggregate([
2 {
3 "$search": {
4 "exists": {
5 "path": "quantities.lemons"
6 }
7 }
8 }
9])

➤ 尝试 Atlas Search Playground 中的示例。

以下示例将 exists 作为复合查询的一部分。

1db.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])

两个文档都具有 type 字段,并且都包含搜索词语 apple。先返回包含 _id: 1 的文档,因为它满足 should 子句的要求。

➤ 尝试 Atlas Search Playground 中的示例。

后退

等于

来年

小关节