

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

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

Amazon DocumentDB 中的`$all`运算符用于匹配其中字段值为数组且包含所有指定元素的文档，无论数组中元素的顺序如何。

**参数**
+ `field`：要检查的字段的名称。
+ `[value1, value2, ...]`：数组中要匹配的值列表。

 

**在`$all`表达式`$elemMatch`中使用**

有关在`$all`表达式中使用`$elemMatch`运算符的限制，请参阅[在 `$all` 表达式中使用 `$elemMatch`](functional-differences.md#functional-differences.elemMatch)。

 

**字段名称中的美元 (\$1)**

有关在嵌套对象中查询`$`前缀字段的限制`$all`，请参阅[字段名称中的美元符号（\$1）和句点（.）](functional-differences.md#functional-differences-dollardot)。

## 示例（MongoDB 外壳）
<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()
```

------