MST

星途 面试题库

面试题:MongoDB中如何基于复合键进行分组聚合

假设有一个集合名为`orders`,文档结构包含`customer_id`(客户ID),`product_category`(产品类别)以及`total_amount`(订单总金额)。请使用MongoDB聚合框架,基于`customer_id`和`product_category`的复合键进行分组,并计算每个分组的订单总金额之和。
38.3万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.orders.aggregate([
    {
        $group: {
            _id: {
                customer_id: "$customer_id",
                product_category: "$product_category"
            },
            totalSum: {
                $sum: "$total_amount"
            }
        }
    }
]);