MST
星途 面试题库

面试题:MongoDB中如何使用分组与投射进行简单的数据聚合

假设有一个MongoDB集合,文档结构如下:{ "name": "张三", "age": 25, "score": 85, "department": "销售部" },现在要求按部门分组,统计每个部门的平均分数,并只返回部门名称和平均分数,写出对应的聚合操作语句。
10.6万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.collection.aggregate([
    {
        $group: {
            _id: "$department",
            averageScore: { $avg: "$score" }
        }
    },
    {
        $project: {
            department: "$_id",
            averageScore: 1,
            _id: 0
        }
    }
])