面试题答案
一键面试假设使用的是MongoDB,以下是实现该需求的聚合管道代码:
db.orders.aggregate([
{
$group: {
_id: "$customerId",
orderCount: { $sum: 1 },
totalAmount: { $sum: "$amount" },
latestOrder: {
$max: {
orderDate: "$orderDate",
amount: "$amount"
}
}
}
},
{
$match: {
orderCount: { $gt: 5 },
totalAmount: { $gt: 1000 }
}
},
{
$sort: {
totalAmount: 1
}
},
{
$project: {
_id: 0,
customerId: "$_id",
orderCount: 1,
totalAmount: 1,
latestOrder: 1
}
}
])
解释:
- $group:
- 使用
$sum
操作符统计每个客户的订单总数orderCount
。 - 使用
$sum
操作符统计每个客户的总金额totalAmount
。 - 使用
$max
操作符找出每个客户最近一笔订单(通过orderDate
的最大值确定),并同时获取该订单的金额。
- 使用
- $match:筛选出订单总数大于5且总金额大于1000的客户。
- $sort:按照总金额升序排列。
- $project:格式化输出,只保留
customerId
、orderCount
、totalAmount
和latestOrder
字段,并去掉默认的_id
字段(重命名为customerId
)。