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

如何在MongoDB聚合中为同集合评论添加回复计数

解决方案

你可以通过自连接聚合的方式,为每个评论统计回复数量,以下是修改后的完整聚合查询:

comment.aggregate([
    // 筛选当前帖子的直接评论
    {
        $match: { postId: mongoose.Types.ObjectId(postid) }
    },
    // 自连接comments集合,获取当前评论的所有回复
    {
        $lookup: {
            from: "comments",
            localField: "_id",
            foreignField: "parentCommentId",
            as: "replies"
        }
    },
    // 关联用户信息
    {            
        $lookup: {
            from: "users",
            localField: "user_id",
            foreignField: "_id",
            as: "user"
        }
    },
    // 投影字段并计算回复数量
    {
        $project: {
            "_id": 1,
            "body": 1,
            "postId": 1,
            "likes": 1,
            "liked": { $in: [ req.authData.nUser._id, "$liked_by" ] },
            "parentCommentId": 1,
            "user._id": 1,
            "user.fullname": 1,
            // 通过$size统计回复数组的长度,得到回复数量
            replyCount: { $size: "$replies" }
        }
    }
])
.sort({"_id": -1})
.exec((err, comments) => {
    // 处理查询结果
});

关键修改说明:

  1. 自连接查询:新增的$lookup操作,将当前评论的_id与其他评论的parentCommentId匹配,把所有回复存入replies临时数组。
  2. 计算回复数量:在$project阶段使用$size运算符,直接统计replies数组的长度,得到该评论的回复总数并命名为replyCount。
  3. 字段保留:在投影中显式包含replyCount,确保最终输出包含该字段。

这个方案会让每个直接评论都带上对应的回复数量,完全符合你期望的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:20:53