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

如何在MongoDB中对递归关系下的关联对象执行计数查询?

实现结论

可以通过单次MongoDB查询完成该统计需求,MongoDB的聚合管道原生支持多集合关联能力,和SQL的多表关联逻辑类似,不需要拆分多次查询。

具体实现逻辑

你可以通过如下聚合管道步骤完成统计:

  • 匹配指定story_id对应的所有Chapter文档
  • 关联Comment集合,拉取每个Chapter绑定的所有评论
  • 关联Reply集合,拉取每个评论对应的所有回复
  • 全局累加统计评论总数和回复总数,求和得到最终结果

示例查询代码

假设你要查询的目标故事ID为ObjectId("目标StoryID"),查询代码如下:

db.chapter.aggregate([
  // 第一步:过滤目标Story关联的所有章节
  {
    $match: { story_id: ObjectId("目标StoryID") }
  },
  // 第二步:关联查询每个章节下的所有评论
  {
    $lookup: {
      from: "comment",
      localField: "id",
      foreignField: "chapter_id",
      as: "comments"
    }
  },
  // 第三步:展开评论数组,方便后续关联回复
  { $unwind: "$comments" },
  // 第四步:关联查询每条评论下的所有回复
  {
    $lookup: {
      from: "reply",
      localField: "comments.id",
      foreignField: "comment_id",
      as: "replies"
    }
  },
  // 第五步:全局统计总数
  {
    $group: {
      _id: null,
      comment_count: { $sum: 1 },
      reply_count: { $sum: { $size: "$replies" } }
    }
  },
  // 第六步:输出最终总评论数(评论+回复)
  {
    $project: {
      _id: 0,
      total_comment_count: { $add: ["$comment_count", "$reply_count"] }
    }
  }
])

补充说明

如果你的数据量较大,建议给chapter.story_id、comment.chapter_id、reply.comment_id三个字段建立索引,可以大幅提升查询效率。


内容的提问来源于stack exchange,提问作者Efraín

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:09:03