MST

星途 面试题库

面试题:MongoDB专家难度查询操作题

有一个复杂的社交网络数据库,其中users集合代表用户,包含friends(数组,存储用户好友的ID)字段;posts集合代表用户发布的帖子,包含author(发布者ID)、likes(数组,存储点赞用户的ID)、comments(数组,每个元素为一个对象,包含author(评论者ID)和text(评论内容))字段。现在需要查询出所有有超过10个好友,且其发布的帖子平均点赞数超过50,同时帖子的平均评论数超过10条的用户信息。请写出完整的聚合查询语句实现该需求。
36.2万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.users.aggregate([
    // 筛选出好友数超过10的用户
    {
        $match: {
            friends: { $size: { $gt: 10 } }
        }
    },
    // 将用户和他们发布的帖子进行关联
    {
        $lookup: {
            from: "posts",
            localField: "_id",
            foreignField: "author",
            as: "userPosts"
        }
    },
    // 筛选出有发布帖子的用户
    {
        $match: {
            userPosts: { $ne: [] }
        }
    },
    // 计算每个用户发布帖子的平均点赞数和平均评论数
    {
        $addFields: {
            averageLikes: {
                $cond: [
                    { $eq: [ { $size: "$userPosts" }, 0 ] },
                    0,
                    {
                        $divide: [
                            { $sum: { $map: { input: "$userPosts", in: { $size: "$$this.likes" } } } },
                            { $size: "$userPosts" }
                        ]
                    }
                ]
            },
            averageComments: {
                $cond: [
                    { $eq: [ { $size: "$userPosts" }, 0 ] },
                    0,
                    {
                        $divide: [
                            { $sum: { $map: { input: "$userPosts", in: { $size: "$$this.comments" } } } },
                            { $size: "$userPosts" }
                        ]
                    }
                ]
            }
        }
    },
    // 筛选出平均点赞数超过50且平均评论数超过10的用户
    {
        $match: {
            averageLikes: { $gt: 50 },
            averageComments: { $gt: 10 }
        }
    }
]);