

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1exists
<a name="exists"></a>

该`$exists`运算符用于检查文档中是否存在字段。 `$exists`在 Amazon DocumentDB 中处理稀疏索引时特别有用，因为索引字段可能不会出现在所有文档中。

要使用您在查询中创建的稀疏索引，必须在涵盖索引的字段中使用 `$exists` 子句。如果省略`$exists`，Amazon DocumentDB 将不会使用稀疏索引进行查询。

**参数**
+ `field`：要检查是否存在的字段名称。
+ `value`：一个布尔值（`true`或`false`），用于指定匹配文档中该字段是否应存在 (`true``false`) 还是不存在 ()。

## 示例（MongoDB 外壳）
<a name="exists-examples"></a>

以下示例演示了如何在`food`集合中的`special_diets`字段上使用带有稀疏索引的`$exists`运算符。

**创建示例文档**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**在 “special\$1diets” 字段上创建稀疏索引**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**查询示例**

```
db.food.find({ "special_diets": { $exists: true } });
```

**输出**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## 代码示例
<a name="exists-code"></a>

要查看使用该`$exists`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('food');

  const result = await collection.find({ "special_diets": { $exists: true } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
import pymongo

client = pymongo.MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['food']

result = list(collection.find({"special_diets": {"$exists": True}}))
print(result)

client.close()
```

------