MST

星途 面试题库

面试题:MongoDB聚合框架排序阶段在复杂嵌套文档中的应用

有一个集合‘orders’,文档结构如下:{‘order_id’: ‘123’, ‘customer’: {‘name’: ‘Alice’, ‘age’: 30}, ‘items’: [{‘product’: ‘A’, ‘quantity’: 2, ‘price’: 10}, {‘product’: ‘B’, ‘quantity’: 1, ‘price’: 20}]} 。要求使用聚合框架,按照每个订单中商品总价(quantity * price)降序排列,返回订单ID及总价最高的商品信息(product、quantity、price)。
15.8万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

在MongoDB中,可使用如下聚合框架实现:

db.orders.aggregate([
    {
        $unwind: "$items"
    },
    {
        $addFields: {
            totalPrice: { $multiply: ["$items.quantity", "$items.price"] }
        }
    },
    {
        $sort: {
            totalPrice: -1
        }
    },
    {
        $group: {
            _id: "$order_id",
            order_id: { $first: "$order_id" },
            maxProductInfo: { $first: "$items" }
        }
    },
    {
        $project: {
            _id: 0,
            order_id: 1,
            product: "$maxProductInfo.product",
            quantity: "$maxProductInfo.quantity",
            price: "$maxProductInfo.price"
        }
    }
]);

上述聚合操作步骤如下:

  1. $unwind:将items数组展开,使得每个文档只包含一个商品信息。
  2. $addFields:计算每个商品的总价totalPrice
  3. $sort:按照totalPrice降序排列。
  4. $group:通过order_id分组,取每组第一个文档(由于前面已经按总价降序,所以第一个文档就是总价最高的商品所在文档),获取订单ID及总价最高的商品信息。
  5. $project:投影输出所需字段,去除_id字段,保留order_idproductquantityprice字段。