$anyElementTrue - Amazon DocumentDB

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

$anyElementTrue

4.0 版的新增内容

$anyElementTrue运算符用于确定数组中是否有任何元素为真。

参数

  • field: 要评估的数组字段。

示例(MongoDB 外壳)

以下示例演示了检查数$anyElementTrue组中是否有任何元素为真值的用法。

创建示例文档

db.grades.insertMany([ { _id: 1, student: 'Tim', scores: [false, false, null] }, { _id: 2, student: 'Bob', scores: [false, 0, false] }, { _id: 3, student: 'Ivy', scores: [false, true, 0] } ])

查询示例

db.grades.aggregate([ { $project: { student: 1, isAnyTrue: { $anyElementTrue: ["$scores"] }, _id: 0 } } ])

输出

[ { student: 'Tim', isAnyTrue: false }, { student: 'Bob', isAnyTrue: false }, { student: 'Ivy', isAnyTrue: true } ]

代码示例

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

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('grades'); const result = await collection.aggregate([ { $project: { student: 1, isAnyTrue: { $anyElementTrue: ["$scores"] }, _id: 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['grades'] result = list(collection.aggregate([ { "$project": { "student": 1, "isAnyTrue": { "$anyElementTrue": ["$scores"] }, "_id": 0 } } ])) print(result) client.close() example()