Docs Menu
Docs Home
/
データベース マニュアル
/ / /

$concatArrays(式演算子)

2 つ以上の配列を連結した 1 つの配列を返します。$concatArrays は、集計アキュムレータまたは配列演算子として使用できます。

$concatArrays

$concatArrays は、次のステージでアキュムレータとして使用できます。

  • $bucket

  • $bucketAuto

  • $group

  • $setWindowFields

集計アキュムレータとして使用する場合、 $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は次の構文をとります。

{ $concatArrays: [ <array1>, <array2>, ... ] }

<array>式は、配列に変換される限り、有効なであれば何でも使用できます。 式の詳細については、「式 」を参照してください。

いずれかの引数が null の値に解決されるか、欠落しているフィールドを参照する場合、$concatArraysnull を返します。

結果
{ $concatArrays: [
[ "hello", " "], [ "world" ]
] }
[ "hello", " ", "world" ]
{ $concatArrays: [
[ "hello", " "],
[ [ "world" ], "again"]
] }
[ "hello", " ", [ "world" ], "again" ]

次のドキュメントを含む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 は、配列と配列に解決される式のみをサポートします。

戻る

$concat

項目一覧