$unwind (聚合管道阶段)

聚合框架中的$unwind阶段用于从输入文档解构数组字段,以便为每个元素输出文档。 每个输出文档都是原始文档的副本,但数组字段的值由单个元素替换。 这对于规范化存储在数组中的数据以及单独对数组的每个元素执行作尤其有用。

语法

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

参数

DESCRIPTION
path 数组字段的字段路径。 这是必需参数。
includeArrayIndex 可选。 要保存未解出元素的数组索引的新字段的名称。
preserveNullAndEmptyArrays 可选。 如果为 true,如果路径为 null、缺失或空数组, $unwind 则输出文档不变。

示例

示例 1:按类别展开销售

若要解构应用商店文档中的 salesByCategory 数组,

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

示例输出

[
  {
    "_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: "$store.promotionEvents",
      includeArrayIndex: "eventIndex"
    }
  }
])

示例输出

[
  {
    "_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
    }
  }
]

这将输出每个文档表示单个提升事件的文档,eventIndex 字段将包含数组中事件的原始索引。

示例 3:在促销活动中展开折扣

若要在每个促销活动中析构折扣数组,并保留没有折扣的文档:

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

示例输出

[
  {
    "_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"
      }
    }
  }
]

这将输出文档,其中每个文档在促销活动中表示单个折扣,并且不保留任何折扣的文档。

  • 查看从 MongoDB 迁移到 Azure Cosmos DB for MongoDB (vCore) 的选项
  • 通过创建帐户开始。