MST

星途 面试题库

面试题:MongoDB Shell脚本之复杂聚合操作

给定一个 'orders' 集合,其中包含 'order_id'(唯一标识)、'customer_id'、'order_date'(日期类型)、'total_amount'(订单总金额,数字类型)和 'items'(一个包含商品信息的数组,每个元素包含 'product_name'、'quantity' 和 'price')。编写一个MongoDB Shell脚本,使用聚合框架完成以下任务:1. 计算每个客户的总订单金额。2. 筛选出总订单金额大于1000的客户。3. 按总订单金额从高到低排序。4. 最终结果只返回客户ID和总订单金额。
24.6万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.orders.aggregate([
    {
        $group: {
            _id: "$customer_id",
            totalOrderAmount: { $sum: "$total_amount" }
        }
    },
    {
        $match: {
            totalOrderAmount: { $gt: 1000 }
        }
    },
    {
        $sort: {
            totalOrderAmount: -1
        }
    },
    {
        $project: {
            customer_id: "$_id",
            totalOrderAmount: 1,
            _id: 0
        }
    }
]);