定義
$anyElementTrue配列をセットとして評価し、いずれかの要素が
trueとfalseである場合はtrueを返します。 空の配列はfalseを返します。$anyElementTrueの構文は次のとおりです。{ $anyElementTrue: [ <expression> ] } <expression>自体は、引数リストを示す外側の配列とは別に、配列に解決される必要があります。 式の詳細については、「 式 」を参照してください。
動作
セットにネストされた配列要素が含まれている場合、 $anyElementTrueはネストされた配列に下降 せず、最上位の配列を評価します。
falseブール値に加えて、 $anyElementTrueは、次のnull 、 0 、 undefined値をfalseとして評価します。 $anyElementTrueは、ゼロ以外の数値と配列を含む他のすべての値をtrueとして評価します。
例 | 結果 |
|---|---|
|
|
|
|
|
|
|
|
例
次のドキュメントを使用して、 surveyという名前のサンプル コレクションを作成します。
db.survey.insertMany( [ { _id: 1, responses: [ true ] }, { _id: 2, responses: [ true, false ] }, { _id: 3, responses: [ ] }, { _id: 4, responses: [ 1, true, "seven" ] }, { _id: 5, responses: [ 0 ] }, { _id: 6, responses: [ [ ] ] }, { _id: 7, responses: [ [ 0 ] ] }, { _id: 8, responses: [ [ false ] ] }, { _id: 9, responses: [ null ] }, { _id: 10, responses: [ undefined ] } ] )
次の操作では、 $anyElementTrue演算子を使用して、 responses配列にtrueと評価される値が含まれているかどうかを判断します。
db.survey.aggregate( [ { $project: { responses: 1, isAnyTrue: { $anyElementTrue: [ "$responses" ] }, _id: 1 } } ] )
[ { _id: 1, responses: [ true ], isAnyTrue: true }, { _id: 2, responses: [ true, false ], isAnyTrue: true }, { _id: 3, responses: [], isAnyTrue: false }, { _id: 4, responses: [ 1, true, 'seven' ], isAnyTrue: true }, { _id: 5, responses: [ 0 ], isAnyTrue: false }, { _id: 6, responses: [ [] ], isAnyTrue: true }, { _id: 7, responses: [ [ 0 ] ], isAnyTrue: true }, { _id: 8, responses: [ [ false ] ], isAnyTrue: true }, { _id: 9, responses: [ null ], isAnyTrue: false }, { _id: 10, responses: [ null ], isAnyTrue: false } ]
結果より:
_id: 1を含むドキュメントはtrueです。これは、responses配列内の要素がtrueと評価されるためです。と
_id: 2_id: 4trueを含むドキュメントは 配列内の少なくとも 1 つの要素がresponsestrueとして評価されているため、 です。_id: 6、_id: 7、_id: 8を持つドキュメントがtrueであるのは、$anyElementTrueが操作を評価した配列であるresponses配列にネストされた配列が含まれているためで、$anyElementTrueは常に次のように評価しますtrue。