MST

星途 面试题库

面试题:MongoDB聚合管道复杂分组操作

在一个名为`orders`的集合中,文档结构有`order_id`(订单编号,唯一)、`customer_id`(客户编号)、`order_date`(订单日期)、`total_amount`(订单总金额)。要求使用聚合管道按`customer_id`分组,统计每个客户的订单数量、订单总金额以及最近一次订单日期,最后按照订单总金额降序排列,写出详细的聚合管道操作。
33.1万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.orders.aggregate([
    {
        $group: {
            _id: "$customer_id",
            order_count: { $sum: 1 },
            total_amount: { $sum: "$total_amount" },
            latest_order_date: { $max: "$order_date" }
        }
    },
    {
        $sort: {
            total_amount: -1
        }
    }
]);