MST

星途 面试题库

面试题:MongoDB子管道操作中嵌套分组与排序的实现

有一个集合 'orders',包含字段 'order_id'、'customer_id'、'order_date' 和 'total_amount'。要求在聚合框架的子管道操作中,先按 'customer_id' 分组,计算每个客户的订单总数和总金额,然后在子管道内按总金额降序排序,最后返回结果。
39.2万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

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

上述代码基于MongoDB进行实现,首先使用$group操作符按customer_id分组并计算订单总数和总金额,然后使用$sort操作符按总金额降序排序。若使用其他数据库,语法会有所不同,例如在SQL中:

SELECT customer_id, COUNT(*) AS order_count, SUM(total_amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY total_amount DESC;

此SQL语句先按customer_id分组统计订单数和总金额,然后按总金额降序排列。