面试题答案
一键面试以下是MongoDB中实现该需求的聚合管道:
[
// 步骤1:展开orders集合中的order_items数组
{
$unwind: "$order_items"
},
// 步骤2:通过product_id将orders集合与products集合进行左连接
{
$lookup: {
from: "products",
localField: "order_items.product_id",
foreignField: "product_id",
as: "product_info"
}
},
// 步骤3:展开lookup后的product_info数组
{
$unwind: "$product_info"
},
// 步骤4:筛选出2023年10月1日之后的订单
{
$match: {
order_date: { $gt: new Date("2023-10-01") }
}
},
// 步骤5:计算每个订单商品的下单金额
{
$addFields: {
order_amount: { $multiply: ["$product_info.price", "$order_items.quantity"] }
}
},
// 步骤6:按category分组,找出每个类别中下单金额最高的产品
{
$group: {
_id: "$product_info.category",
max_order_amount: { $max: "$order_amount" },
product_id: { $first: "$product_info.product_id" },
product_name: { $first: "$product_info.product_name" },
price: { $first: "$product_info.price" }
}
},
// 步骤7:重命名_id字段为category
{
$project: {
category: "$_id",
product_id: 1,
product_name: 1,
price: 1,
_id: 0
}
}
]
- $unwind: 展开
orders
集合中的order_items
数组,以便后续处理每个订单中的商品。 - $lookup: 通过
product_id
将orders
集合与products
集合进行左连接,将匹配的产品信息添加到结果文档中。 - $unwind: 展开
lookup
操作后生成的product_info
数组。 - $match: 筛选出
order_date
在2023年10月1日之后的订单。 - $addFields: 计算每个订单商品的下单金额,通过产品价格和购买数量相乘。
- $group: 按产品类别分组,找出每个类别中下单金额最高的产品,并保留其
product_id
、product_name
和price
。 - $project: 重命名
_id
字段为category
,并去除_id
字段,使结果文档结构更清晰。