你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
该 $reduce 运算符用于将表达式应用于数组中的每个元素,并将结果累积到单个值中。 此运算符可用于执行需要循环访问数组元素并聚合其值的作。
Syntax
$reduce: {
input: <array>,
initialValue: <expression>,
in: <expression>
}
参数
| 参数 | Description |
|---|---|
input |
要循环访问的数组。 |
initialValue |
数组迭代开始前设置的初始累积值。 |
in |
一个计算结果为数组中每个元素的累积值的有效表达式。 |
例子
请考虑商店集合中的这个示例文档。
{
"_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:聚合数组值
此查询演示如何用于 $reduce 对数组中 salesByCategory 不同类别的总销售额求和。
db.stores.aggregate([{
$match: {
_id: "988d2dd1-2faa-4072-b420-b91b95cbfd60"
}
}, {
$project: {
totalSalesByCategory: {
$reduce: {
input: "$sales.salesByCategory.totalSales",
initialValue: 0,
in: {
$add: ["$$value", "$$this"]
}
}
}
}
}])
查询返回以下结果。
[
{
"_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60",
"totalSalesByCategory": 149849
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。