$reduce演算子は、配列内の各要素に式を適用し、結果を 1 つの値に蓄積するために使用されます。 この演算子は、配列要素を反復処理し、その値を集計する必要がある操作を実行する場合に便利です。
構文
$reduce: {
input: <array>,
initialValue: <expression>,
in: <expression>
}
パラメーター
| パラメーター | Description |
|---|---|
input |
反復処理する配列。 |
initialValue |
配列の反復が開始される前に設定された初期累積値。 |
in |
配列内の各要素の累積値に評価される有効な式。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
例 1: 配列値を集計する
このクエリでは、 $reduce を使用して、 salesByCategory 配列内のさまざまなカテゴリの売上合計を合計する方法を示します。
db.stores.aggregate([{
$match: {
_id: "988d2dd1-2faa-4072-b420-b91b95cbfd60"
}
}, {
$project: {
totalSalesByCategory: {
$reduce: {
input: "$sales.salesByCategory.totalSales",
initialValue: 0,
in: {
$add: ["$$value", "$$this"]
}
}
}
}
}])
クエリは次の結果を返します。
[
{
"_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60",
"totalSalesByCategory": 149849
}
]
関連コンテンツ
- MongoDB から Azure DocumentDB に移行するためのオプションを確認します。
- MongoDB との機能の互換性について詳しくは、こちらをご覧ください。