$addFields (聚合管道阶段)

聚合管道中的 $addFields 阶段用于向文档添加新字段。 它还可用于重置现有字段的值。 当需要基于现有数据创建新字段或修改文档中的现有字段时,此阶段特别有用。

语法

$addFields 阶段的基本语法如下:

{
  $addFields: {
    <newField1>: <expression1>,
    <newField2>: <expression2>,
    ...
  }
}

参数

DESCRIPTION
newField1 要添加的新字段或要修改的现有字段的名称。
expression1 用于计算 newField1 值的表达式。

示例

示例 1:添加新字段

假设我们有一个名为商店的集合,其中包含类似于提供的 JSON 结构的文档。 若要添加计算促销活动数的新字段 totalDiscountEvents,可以使用以下聚合管道:

db.stores.aggregate([
  {
    $addFields: {
      totalDiscountEvents: { $size: "$store.promotionEvents" }
    }
  }
])

示例输出

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"]
    },
    "totalDiscountEvents": 3
  }
]

示例 2:修改现有字段

如果想要添加汇总全职员工和兼职员工的字段 totalStaffCount,可以使用:

db.stores.aggregate([
  {
    $addFields: {
      totalStaffCount: {
        $add: ["$store.staff.totalStaff.fullTime", "$store.staff.totalStaff.partTime"]
      }
    }
  }
])

示例输出

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "staff": {
        "totalStaff": {
          "fullTime": 12,
          "partTime": 8
        }
      }
    },
    "totalStaffCount": 20
  }
]

示例 3:添加嵌套字段

若要添加将纬度和经度合并到数组中的嵌套字段 location.coordinates,请使用:

db.stores.aggregate([
  {
    $addFields: {
      "store.location.coordinates": ["$store.location.lat", "$store.location.lon"]
    }
  }
])

示例输出

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "location": {
        "lat": 47.6097,
        "lon": -122.3331,
        "coordinates": [47.6097, -122.3331]
      }
    }
  }
]
  • 查看从 MongoDB 迁移到 Azure Cosmos DB for MongoDB (vCore) 的选项
  • 通过创建帐户开始。