$unwind

集計フレームワークの $unwind ステージは、入力ドキュメントから配列フィールドを分解し、各要素に対応するドキュメントを出力するために使用されます。 各出力ドキュメントは元のドキュメントのコピーですが、配列フィールドの値が 1 つの要素に置き換えられます。 これは、配列に格納されたデータを正規化したり、配列の各要素に対して個別に操作を実行したりする場合に特に便利です。

構文

{
  $unwind: {
    path: <field path>,
    includeArrayIndex: <string>, // Optional
    preserveNullAndEmptyArrays: <boolean> // Optional
  }
}

パラメーター

パラメーター Description
path 配列フィールドへのフィールド パス。 これは必須パラメーターです。
includeArrayIndex Optional. 展開された要素の配列インデックスを保持する新しいフィールドの名前。
preserveNullAndEmptyArrays Optional. true を設定すると、パスが null、存在しない、または空の配列である場合でも、$unwind によってドキュメントが変更されることなく出力されます。

例示

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: カテゴリ別のアンワインド売上

ストア ドキュメント内の salesByCategory 配列を分解するには:

db.stores.aggregate([
  {
    $unwind: "$sales.salesByCategory"
  }
])

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "sales": {
        "totalSales": 15000,
        "salesByCategory": {
          "category": "Electronics",
          "totalSales": 5000
        }
      }
    }
  },
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "sales": {
        "totalSales": 15000,
        "salesByCategory": {
          "category": "Clothing",
          "totalSales": 10000
        }
      }
    }
  }
]

例 2: 配列インデックスを使用したアンワインド 昇格イベント

promotionEvents 配列を分解し、出力に配列インデックスを含めるには、次のようにします。

db.stores.aggregate([
  {
    $unwind: {
      path: "$promotionEvents",
      includeArrayIndex: "eventIndex"
    }
  }
])

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": {
        "eventName": "Summer Sale",
        "eventDate": ISODate("2024-08-01T00:00:00Z")
      },
      "eventIndex": 0
    }
  },
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": {
        "eventName": "Black Friday",
        "eventDate": ISODate("2024-11-25T00:00:00Z")
      },
      "eventIndex": 1
    }
  }
]

例 3: 降格イベント内でのアンワインド割引

各販売促進イベント内の discounts 配列を分解し、割引なしでドキュメントを保存するには:

db.stores.aggregate([
  {
    $unwind: {
      path: "$promotionEvents.discounts",
      preserveNullAndEmptyArrays: true
    }
  }
])

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": {
        "eventName": "Summer Sale",
        "discounts": {
          "discountType": "Percentage",
          "discountAmount": 20
        }
      }
    }
  },
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": {
        "eventName": "Black Friday"
      }
    }
  }
]