定義
2 つ以上の配列を連結した 1 つの配列を返します。$concatArrays
は、集計アキュムレータまたは配列演算子として使用できます。
集計アキュムレータ
$concatArrays
は、次のステージでアキュムレータとして使用できます。
構文
集計アキュムレータとして使用する場合、 $concatArrays
は次の構文をとります。
{ $concatArrays: "<array field>" }
動作
null
であるか、null
に解決される引数は結果に含まれます。欠落しているフィールドを参照する引数は結果に含まれません。
例
次のドキュメントを含むsales
という名前のコレクションを作成します。
db.sales.insertMany( [ { _id: 1, items: [ "laptop", "tablet" ], location: "NYC" }, { _id: 2, items: [ "phone", "tablet" ], location: "NYC" }, { _id: 3, location: "NYC" }, { _id: 4, items: [ "desktop", { "accessories": [ "mouse", "keyboard"] } ], location: "NYC" } ] )
この例では、$concatArrays
をアキュムレータとして使用する方法を示します。この例では、location
フィールドでグループ化するときに、すべての items
配列の要素を結合します。
db.sales.aggregate( [ { $group: { _id: "$location", array: { "$concatArrays": "$items" } } } ] )
この操作では、次の結果を返します。
[ { "_id": "NYC", "array": [ "laptop", "tablet", "phone", "tablet", "desktop", { "accessories": [ "mouse", "keyboard"] } ] } ]
配列演算子
構文
配列演算子として使用する場合、 $concatArrays
は次の構文をとります。
{ $concatArrays: [ <array1>, <array2>, ... ] }
動作
<array>
式は、配列に変換される限り、有効な式であれば何でも使用できます。 式の詳細については、「式 」を参照してください。
いずれかの引数が null
の値に解決されるか、欠落しているフィールドを参照する場合、$concatArrays
は null
を返します。
例 | 結果 | |||||
---|---|---|---|---|---|---|
|
| |||||
|
|
例
次のドキュメントを含む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: [ ] } ] )
次の例では、instock
配列と ordered
配列を連結します。
db.warehouses.aggregate( [ { $project: { items: { $concatArrays: [ "$instock", "$ordered" ] } } } ] )
この操作は次の結果を返します。
[ { _id : 1, items : [ "chocolate", "butter", "apples" ] }, { _id : 2, items : null }, { _id : 3, items : [ "pears", "pecans", "cherries" ] }, { _id : 4, items : [ "ice cream" ] } ]
制限
$concatArrays
は、配列と配列に解決される式のみをサポートします。