面试题答案
一键面试在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"
}
}
]);
上述聚合操作步骤如下:
- $unwind:将
items
数组展开,使得每个文档只包含一个商品信息。 - $addFields:计算每个商品的总价
totalPrice
。 - $sort:按照
totalPrice
降序排列。 - $group:通过
order_id
分组,取每组第一个文档(由于前面已经按总价降序,所以第一个文档就是总价最高的商品所在文档),获取订单ID及总价最高的商品信息。 - $project:投影输出所需字段,去除
_id
字段,保留order_id
、product
、quantity
和price
字段。