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

MongoDB关联post、comment集合按author分组统计total_votes总和

MongoDB多集合按作者统计总投票数实现方案

要实现按author维度统计post和comment两个集合的total_votes总和,可以使用MongoDB聚合管道搭配$unionWith操作符完成,具体查询语句如下:

db.post.aggregate([
  // 合并comment集合的所有文档到当前结果流
  {
    $unionWith: "comment"
  },
  // 按author分组,累加所有total_votes
  {
    $group: {
      _id: "$author",
      total_votes: { $sum: "$total_votes" }
    }
  },
  // 调整输出字段名,和预期格式对齐
  {
    $project: {
      _id: 0,
      author: "$_id",
      total_votes: 1
    }
  },
  // 可选:按总投票数倒序排序,和你给出的预期输出顺序一致
  {
    $sort: { total_votes: -1 }
  }
])

注意事项

  • $unionWith是MongoDB 4.4及以上版本支持的操作符,用于合并两个集合的文档流
  • 你给出的示例数据中存在author拼写不一致的笔误(比如tes1@gmail.com和test1@gmail.com),实际运行时会按照数据中的真实author值聚合,修改数据拼写即可得到你给出的预期结果
  • 如果使用低于4.4的MongoDB版本,可以分别对两个集合做分组聚合,再在应用层合并求和即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:06