面试题答案
一键面试from pymongo import MongoClient
def get_top_customers():
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
orders = db['orders']
pipeline = [
{
'$unwind': '$products'
},
{
'$group': {
'_id': '$customer_id',
'total_spent': {
'$sum': {
'$multiply': ['$products.quantity', '$products.price']
}
}
}
},
{
'$sort': {
'total_spent': -1
}
},
{
'$limit': 10
}
]
result = list(orders.aggregate(pipeline))
for customer in result:
print(f"Customer ID: {customer['_id']}, Total Spent: {customer['total_spent']}")
if __name__ == "__main__":
get_top_customers()
在上述代码中:
- 首先使用
MongoClient
连接到本地的MongoDB数据库(根据实际情况修改连接字符串)。 - 定义了一个聚合管道:
- 使用
$unwind
操作符展开products
数组,以便后续对每个产品进行计算。 - 使用
$group
操作符按customer_id
分组,并计算每个客户的总消费金额(通过$multiply
计算每个产品的总价并通过$sum
累加)。 - 使用
$sort
操作符按总消费金额从高到低排序。 - 使用
$limit
操作符只取前10个客户。
- 使用
- 最后遍历结果并打印每个客户的ID和总消费金额。