$sum (总和)

$sum 运算符计算与筛选条件匹配的字段或表达式的数值之和。

Syntax

{
  $sum: <field or expression>
}

参数

参数 Description
<field or expression> 要计算其总和的字段或表达式。 可以是字段、数值或表达式。

例子

请考虑商店集合中的这个示例文档。

{
    "_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:使用$sum$group

若要计算 2023 年所有促销事件中每个类别的总折扣百分比:

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $unwind: "$promotionEvents.discounts"
    },
    {
        $match: {
            "promotionEvents.promotionalDates.startDate.Year": 2023
        }
    },
    {
        $group: {
            _id: "$promotionEvents.discounts.categoryName",
            totalDiscountIn2023: {
                $sum: "$promotionEvents.discounts.discountPercentage"
            }
        }
    },
    {
        $project: {
            _id: 0,
            categoryName: "$_id",
            totalDiscountIn2023: 1
        }
    }
])

此查询返回以下结果:

[
    {
        "categoryName": "Glass Frames",
        "totalDiscountIn2023": 25
    },
    {
        "categoryName": "Picture Hanging Supplies",
        "totalDiscountIn2023": 14
    }
]

示例 2:使用$sum$bucket

若要在定义的销售边界内获取总销售额,

db.stores.aggregate([{
    $bucket: {
        groupBy: "$sales.totalSales", // Field to group by
        boundaries: [0, 10000, 20000, 50000, 100000], // Sales ranges
        default: "Other", // Default bucket for values outside the defined ranges
        output: {
            totalSalesSum: {
                $sum: "$sales.totalSales"
            }, // Sum the sales for each bucket
            count: {
                $sum: 1
            } // Count the number of documents in each bucket
        }
    }
}])

此查询返回以下结果:

[
    {
        "_id": "Other",
        "totalSalesSum": 454981695,
        "count": 3001
    },
    {
        "_id": 0,
        "totalSalesSum": 20033725,
        "count": 3903
    },
    {
        "_id": 10000,
        "totalSalesSum": 71303703,
        "count": 4712
    },
    {
        "_id": 50000,
        "totalSalesSum": 756168541,
        "count": 11025
    },
    {
        "_id": 20000,
        "totalSalesSum": 678976078,
        "count": 18861
    }
]

示例 3:使用$sum$setWindowFields

若要计算 2023 年促销的每个销售类别的总折扣:

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $unwind: "$promotionEvents.discounts"
    },
    {
        $match: {
            "promotionEvents.promotionalDates.startDate.Year": 2023
        }
    },
    {
        $setWindowFields: {
            partitionBy: "$promotionEvents.discounts.categoryName", // Group by categoryName
            output: {
                totalDiscountIn2023: {
                    $sum: "$promotionEvents.discounts.discountPercentage", // Sum discount percentage
                    window: {
                        documents: ["unbounded", "unbounded"] // Aggregate over all documents in the partition
                    }
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            categoryName: "$promotionEvents.discounts.categoryName",
            discountPercentage: "$promotionEvents.discounts.discountPercentage",
            totalDiscountIn2023: 1
        }
    },
    {
        $limit: 5
    }
])

此查询返回以下结果:

[
    {
        "totalDiscountIn2023": 1106,
        "categoryName": "2-in-1 Laptops",
        "discountPercentage": 25
    },
    {
        "totalDiscountIn2023": 1106,
        "categoryName": "2-in-1 Laptops",
        "discountPercentage": 22
    },
    {
        "totalDiscountIn2023": 1106,
        "categoryName": "2-in-1 Laptops",
        "discountPercentage": 19
    },
    {
        "totalDiscountIn2023": 1106,
        "categoryName": "2-in-1 Laptops",
        "discountPercentage": 17
    },
    {
        "totalDiscountIn2023": 1106,
        "categoryName": "2-in-1 Laptops",
        "discountPercentage": 10
    }
]