You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB中如何统计关联集合里每个帖子的评论数?

实现帖子评论数量统计的两种方案

方案一:直接返回comment_count字段(对应形式二)

推荐这种结构,更简洁直观,性能优化也更灵活。

方式1:基于现有查询快速改造

在原$lookup后添加$addFields阶段,用$size操作符直接计算关联评论数组的长度:

post.aggregate([
    {
        $lookup: {
            from: 'comment',
            localField: '_id',
            foreignField: 'postId',
            as: 'post_comment'
        }
    },
    {
        $addFields: {
            comment_count: { $size: '$post_comment' }, // 计算评论数量
            post_comment: '$$REMOVE' // 可选:不需要保留评论详情数组时移除
        }
    }
])

方式2:带管道的$lookup(性能更优)

直接在关联阶段就统计评论数,避免拉取所有评论详情,适合数据量大的场景:

post.aggregate([
    {
        $lookup: {
            from: 'comment',
            let: { post_id: '$_id' },
            pipeline: [
                { $match: { $expr: { $eq: ['$postId', '$$post_id'] } } },
                { $count: 'count' } // 统计当前帖子的评论总数
            ],
            as: 'comment_temp'
        }
    },
    {
        $addFields: {
            comment_count: { 
                $ifNull: [{ $arrayElemAt: ['$comment_temp.count', 0] }, 0] 
            },
            comment_temp: '$$REMOVE'
        }
    }
])

这个方案会自动处理无评论的帖子,返回comment_count: 0。


方案二:返回post_comment数组包含count对象(对应形式一)

方式1:现有查询改造

在$lookup后替换post_comment字段为包含统计值的数组:

post.aggregate([
    {
        $lookup: {
            from: 'comment',
            localField: '_id',
            foreignField: 'postId',
            as: 'post_comment'
        }
    },
    {
        $addFields: {
            post_comment: [
                { count: { $size: '$post_comment' } }
            ]
        }
    }
])

方式2:带管道的$lookup直接生成

在关联阶段直接返回统计结构,同时兼容无评论的情况:

post.aggregate([
    {
        $lookup: {
            from: 'comment',
            let: { post_id: '$_id' },
            pipeline: [
                { $match: { $expr: { $eq: ['$postId', '$$post_id'] } } },
                { $count: 'count' },
                { $project: { _id: 0 } }
            ],
            as: 'post_comment'
        }
    },
    {
        $addFields: {
            post_comment: {
                $cond: {
                    if: { $eq: ['$post_comment', []] },
                    then: [{ count: 0 }],
                    else: '$post_comment'
                }
            }
        }
    }
])

内容的提问来源于stack exchange,提问作者Snookums

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:09:54