$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) 的选项
  • 通过创建帐户开始。