MST

星途 面试题库

面试题:MongoDB复杂条件下集合所有文档的聚合查询及嵌套处理

在MongoDB的`orders`集合中,每个文档包含`order_id`、`customer_id`、`order_items`(数组,每个元素包含`product_name`、`quantity`、`price`)等字段。要求查询出每个`customer_id`下,所有`order_items`中`product_name`为`laptop`且`quantity`大于5的订单总金额(订单总金额 = 该订单下所有`laptop`产品的`quantity` * `price`之和),并按总金额降序排列,写出实现该功能的聚合查询语句。
12.6万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.orders.aggregate([
    {
        $unwind: "$order_items"
    },
    {
        $match: {
            "order_items.product_name": "laptop",
            "order_items.quantity": { $gt: 5 }
        }
    },
    {
        $group: {
            _id: "$customer_id",
            totalAmount: {
                $sum: {
                    $multiply: ["$order_items.quantity", "$order_items.price"]
                }
            }
        }
    },
    {
        $sort: {
            totalAmount: -1
        }
    }
]);