$allElementsTrue - Amazon DocumentDB

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

$allElementsTrue

4.0 版的新增内容

$allElementsTrue运算符用于检查数组中所有元素的计算结果是否为真值。

参数

  • expression: 计算结果为数组的表达式。

示例(MongoDB 外壳)

以下示例演示了检查数组中所有元素是否为真时的用法。$allElementsTrue

创建示例文档

db.collection.insert([ { "name": "John", "scores": [100, 90, 80] }, { "name": "Jane", "scores": [80, 85, 0] }, { "name": "Bob", "scores": [90, 95, null] } ])

查询示例

db.collection.find({ "scores": { "$allElementsTrue": [{ "$gt": 0 }] } })

输出

[ { "_id" : ObjectId("..."), "name" : "John", "scores" : [ 100, 90, 80 ] }, { "_id" : ObjectId("..."), "name" : "Bob", "scores" : [ 90, 95, null ] } ]

在此示例中,查询检查scores数组中的所有元素是否都大于 0。之所以排除带的"name": "Jane"文档,是因为该scores数组包含一个 0,这是一个虚假值。

代码示例

要查看使用该$allElementsTrue命令的代码示例,请选择要使用的语言的选项卡:

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('collection'); const result = await collection.find({ "scores": { "$allElementsTrue": [{ "$gt": 0 }] } }).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['collection'] result = list(collection.find({ "scores": {"$allElementsTrue": [{"$gt": 0}]} })) print(result) client.close() example()