

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

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

Amazon DocumentDB 中的`$all`運算子用於比對欄位值為陣列的文件，並包含所有指定的元素，無論陣列中的元素順序為何。

**參數**
+ `field`：要檢查的欄位名稱。
+ `[value1, value2, ...]`：陣列中要比對的值清單。

 

**在`$all`表達式`$elemMatch`內使用**

[在`$all`表達式`$elemMatch`內使用](functional-differences.md#functional-differences.elemMatch) 如需在`$all`表達式中使用`$elemMatch`運算子的限制，請參閱 。

 

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

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

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

下列範例示範 `$all`運算子的使用情況，以擷取「顏色」欄位為包含「紅色」和「藍色」的陣列的文件。

**建立範例文件**

```
db.example.insertMany([
  { "Item": "Pen", "Colors": ["Red", "Blue", "Green"] },
  { "Item": "Notebook", "Colors": ["Blue", "White"] },
  { "Item": "Poster Paint", "Colors": ["Red", "Yellow", "White"] }
])
```

**查詢範例**

```
db.example.find({ "Colors": { $all: ["Red", "Blue"] } }).pretty()
```

**輸出**

```
{
  "_id" : ObjectId("6137d6c5b3a1d35e0b6ee6ad"),
  "Item" : "Pen",
  "Colors" : [ 
          "Red", 
          "Blue", 
          "Green" 
  ]
}
```

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

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

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

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

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

  const result = await collection.find({ "Colors": { $all: ["Red", "Blue"] } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

def example():
    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['example']

    result = list(collection.find({ "Colors": { "$all": ["Red", "Blue"] } }))
    print(result)

    client.close()

example()
```

------