MST
星途 面试题库

面试题:MongoDB聚合框架下复杂文档查询及分析

在MongoDB的`sales`集合里,文档结构为{sale_id: 1, region: 'North', products: [{product_id: 'P001', sales: 100, revenue: 1000}, {product_id: 'P002', sales: 50, revenue: 750}], total_revenue: 1750}。使用聚合框架,按地区统计总销售额(所有产品的销售数量之和)以及总营收,并按照总营收从高到低排序,只返回总销售额大于100且总营收大于1500的结果。
45.0万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.sales.aggregate([
    {
        $unwind: "$products"
    },
    {
        $group: {
            _id: "$region",
            total_sales: { $sum: "$products.sales" },
            total_revenue: { $sum: "$products.revenue" }
        }
    },
    {
        $match: {
            total_sales: { $gt: 100 },
            total_revenue: { $gt: 1500 }
        }
    },
    {
        $sort: {
            total_revenue: -1
        }
    }
]);