$all - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

$all

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

参数

  • field:要检查的字段的名称。

  • [value1, value2, ...]:数组中要匹配的值列表。

 

$all表达式$elemMatch中使用

有关在$all表达式中使用$elemMatch运算符的限制,请参阅在 $all 表达式中使用 $elemMatch

 

字段名称中的美元 ($)

有关在嵌套对象中查询$前缀字段的限制$all,请参阅字段名称中的美元符号($)和句点(.)

示例(MongoDB 外壳)

以下示例演示如何使用$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" ] }

代码示例

要查看使用该$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()