MST

星途 面试题库

面试题:MongoDB数组类型数据查询之聚合与数组操作深度结合

在集合sales中,每个文档包含一个数组transactions,每个transaction是一个文档,有amount(交易金额)、date(交易日期)和customer(客户信息文档,包含customerId和customerName)。例如:{storeId: 1, transactions: [{amount: 100, date: ISODate('2023 - 01 - 01'), customer: {customerId: 'C001', customerName: 'Bob'}}, {amount: 200, date: ISODate('2023 - 01 - 02'), customer: {customerId: 'C002', customerName: 'Eve'}}]}。使用聚合操作,找出每个客户在2023年1月的总交易金额,结果按总交易金额降序排列,并且只返回总交易金额大于100的客户信息(customerId和customerName)及总交易金额。
43.1万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.sales.aggregate([
    {
        $unwind: "$transactions"
    },
    {
        $match: {
            "transactions.date": {
                $gte: new ISODate("2023-01-01"),
                $lt: new ISODate("2023-02-01")
            }
        }
    },
    {
        $group: {
            _id: {
                customerId: "$transactions.customer.customerId",
                customerName: "$transactions.customer.customerName"
            },
            totalAmount: {
                $sum: "$transactions.amount"
            }
        }
    },
    {
        $match: {
            totalAmount: {
                $gt: 100
            }
        }
    },
    {
        $sort: {
            totalAmount: -1
        }
    },
    {
        $project: {
            _id: 0,
            customerId: "$_id.customerId",
            customerName: "$_id.customerName",
            totalAmount: 1
        }
    }
]);