MST

星途 面试题库

面试题:MongoDB多键分组中的复杂计算

在MongoDB集合中,文档结构为{ 'product': '手机', 'category': '电子产品', 'price': 5000, 'quantity': 10 } 。要求按'category'和'product'多键分组,计算每个分组的总销售额(price * quantity),并找出总销售额最高的分组。请写出实现的聚合管道。
29.8万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
[
    {
        "$group": {
            "_id": {
                "category": "$category",
                "product": "$product"
            },
            "totalSales": {
                "$sum": {
                    "$multiply": ["$price", "$quantity"]
                }
            }
        }
    },
    {
        "$sort": {
            "totalSales": -1
        }
    },
    {
        "$limit": 1
    }
]