MST

星途 面试题库

面试题:Python在MongoDB中复杂聚合及嵌套数据处理

在Python连接的MongoDB数据库里,有一个`orders`集合,每个订单文档包含`order_id`(订单ID)、`customer_id`(客户ID)、`order_date`(订单日期)以及一个`products`数组,`products`数组中的每个元素包含`product_name`(产品名称)、`quantity`(数量)和`price`(价格)。请使用Python的`pymongo`库编写代码,查询出每个客户的总消费金额,并按照总消费金额从高到低排序,只显示消费金额最高的前10个客户。
11.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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()

在上述代码中:

  1. 首先使用MongoClient连接到本地的MongoDB数据库(根据实际情况修改连接字符串)。
  2. 定义了一个聚合管道:
    • 使用$unwind操作符展开products数组,以便后续对每个产品进行计算。
    • 使用$group操作符按customer_id分组,并计算每个客户的总消费金额(通过$multiply计算每个产品的总价并通过$sum累加)。
    • 使用$sort操作符按总消费金额从高到低排序。
    • 使用$limit操作符只取前10个客户。
  3. 最后遍历结果并打印每个客户的ID和总消费金额。