[
// 过滤出2023年的订单
{
$match: {
order_date: {
$gte: new Date('2023-01-01'),
$lt: new Date('2024-01-01')
}
}
},
// 展开items数组,以便处理每个商品项
{
$unwind: "$items"
},
// 计算每个订单中每个商品项的金额
{
$addFields: {
item_total: {
$multiply: ["$items.quantity", "$items.price"]
}
}
},
// 计算每个订单的总金额
{
$group: {
_id: "$order_id",
customer_id: { $first: "$customer_id" },
order_amount: { $sum: "$item_total" }
}
},
// 按customer_id分组,汇总每个客户的总金额
{
$group: {
_id: "$customer_id",
total_amount: { $sum: "$order_amount" }
}
},
// 过滤出总金额大于1000的客户
{
$match: {
total_amount: { $gt: 1000 }
}
},
// 重命名字段
{
$project: {
customer_id: "$_id",
total_amount: 1,
_id: 0
}
}
]