聚合管道中的 $addFields 阶段用于向文档添加新字段。 它还可用于重置现有字段的值。 当需要基于现有数据创建新字段或修改文档中的现有字段时,此阶段特别有用。
语法
{
$addFields: {
<newField1>: <expression1>,
<newField2>: <expression2>,
...
}
}
参数
参数 | DESCRIPTION |
---|---|
newField1 |
要添加的新字段或要修改的现有字段的名称。 |
expression1 |
用于计算 newField1 值的表达式。 |
例子
请考虑商店集合中的这个示例文档。
{
"_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:添加新字段
此查询添加了一个新的字段 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) 的选项
- 通过创建帐户开始。