

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

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

Amazon DocumentDB 中的`$in`運算子是一種邏輯查詢運算子，可讓您尋找欄位值等於陣列中指定任何值的文件。

**參數**
+ `field`：要檢查所提供陣列的欄位。
+ `[value1, value2, ...]`：要比對指定欄位的值陣列。

 

**欄位名稱中的美元 (`$`)**

[欄位名稱中的 Dollar(\$1) 和 dot(.)](functional-differences.md#functional-differences-dollardot) 如需在巢狀物件`$in`中查詢字`$`首欄位的限制，請參閱 。

## 範例 (MongoDB Shell)
<a name="in-examples"></a>

下列範例示範如何使用 `$in`運算子來尋找 `color` 欄位為所提供陣列中其中一個值的文件。

**建立範例文件**

```
db.colors.insertMany([
  { "_id": 1, "color": "red" },
  { "_id": 2, "color": "green" },
  { "_id": 3, "color": "blue" },
  { "_id": 4, "color": "yellow" },
  { "_id": 5, "color": "purple" }
])
```

**查詢範例**

```
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
```

**輸出**

```
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
```

## 程式碼範例
<a name="in-code"></a>

若要檢視使用 `$in`命令的程式碼範例，請選擇您要使用的語言標籤：

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

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

async function findByIn() {
  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('colors');

  const result = await collection.find({ "color": { "$in": ["red", "blue", "purple"] } }).toArray();
  console.log(result);

  await client.close();
}

findByIn();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.find({ "color": { "$in": ["red", "blue", "purple"] } }))
    print(result)

    client.close()

find_by_in()
```

------