

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

`$exists` 運算子用於檢查某個欄位是否存在於文件中。在 Amazon DocumentDB 中使用稀疏索引時`$exists`特別有用，其中索引欄位可能不存在於所有文件中。

若要使用您在查詢中建立的稀疏索引，您必須在涵蓋索引的欄位上使用 `$exists` 子句。如果您省略 `$exists`，Amazon DocumentDB 將不會使用查詢的稀疏索引。

**參數**
+ `field`：要檢查是否存在的欄位名稱。
+ `value`：布林值 (`true` 或 `false`)，指定相符文件中的欄位是否應該存在 (`true`) 或不存在 (`false`)。

## 範例 (MongoDB Shell)
<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()
```

------