$isArray (aggregation)
定義
$isArray
オペランドが配列であるかどうかを判断します。ブール値を返します。
$isArray
の構文は次のとおりです。{ $isArray: [ <expression> ] }
動作
The <expression>
can be any valid 式. For more information on expressions, see
式演算子.
例 | 結果 | ノート |
---|---|---|
|
|
|
|
|
|
|
|
|
注意
Aggregation expressions accept a variable number of arguments. These arguments are normally passed as an array. However, when the argument is a single value, you can simplify your code by passing the argument directly without wrapping it in an array.
例
次のドキュメントを含むwarehouses
という名前のコレクションを作成します。
db.warehouses.insertMany( [ { _id : 1, instock: [ "chocolate" ], ordered: [ "butter", "apples" ] }, { _id : 2, instock: [ "apples", "pudding", "pie" ] }, { _id : 3, instock: [ "pears", "pecans" ], ordered: [ "cherries" ] }, { _id : 4, instock: [ "ice cream" ], ordered: [ ] } ] )
Check if the instock
and the ordered
fields are arrays. If both
fields are arrays, concatenate them:
db.warehouses.aggregate( [ { $project: { items: { $cond: { if: { $and: [ { $isArray: "$instock" }, { $isArray: "$ordered" } ] }, then: { $concatArrays: [ "$instock", "$ordered" ] }, else: "One or more fields is not an array." } } } } ] )
{ _id : 1, items : [ "chocolate", "butter", "apples" ] } { _id : 2, items : "One or more fields is not an array." } { _id : 3, items : [ "pears", "pecans", "cherries" ] } { _id : 4, items : [ "ice cream" ] }
以下も参照してください。