MST

星途 面试题库

面试题:MongoDB $avg累加器函数在复杂用户行为数据分析中的应用

有一个MongoDB集合user_actions,文档结构为{user_id: 用户ID, action_type: 行为类型, action_time: 行为发生时间, value: 行为相关数值}。需求是按天统计不同行为类型下每个用户的行为value的平均值,且只统计每天行为次数大于10次的用户数据,用聚合操作实现,其中要用到$avg累加器函数。
10.5万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.user_actions.aggregate([
    {
        $group: {
            _id: {
                user_id: "$user_id",
                action_type: "$action_type",
                action_date: { $dateToString: { format: "%Y-%m-%d", date: "$action_time" } }
            },
            total_value: { $sum: "$value" },
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gt: 10 }
        }
    },
    {
        $group: {
            _id: {
                action_type: "$_id.action_type",
                action_date: "$_id.action_date"
            },
            average_value: { $avg: "$total_value" }
        }
    }
]);