You need to enable JavaScript to run this app. 如何编写按name分组统计文档填充占比的正确MongoDB查询
优惠活动
大模型
产品
解决方案
定价
更多

如何编写按name分组统计文档填充占比的正确MongoDB查询

符合需求的MongoDB查询语句

请将你的集合名替换为实际业务使用的集合名称

db.你的集合名.aggregate([
  // 按name分组,统计组内总文档数、fill非0的文档数
  {
    $group: {
      _id: "$name",
      totalDocs: { $sum: 1 },
      fillcount: {
        $sum: {
          $cond: [{ $ne: ["$fill", 0] }, 1, 0]
        }
      }
    }
  },
  // 输出符合格式的字段,计算填充占比
  {
    $project: {
      _id: 0,
      name: "$_id",
      fillcount: 1,
      fillpercentagetototaldocument: {
        $concat: [
          // 计算占比*100后截断小数,拼接%符号
          { $toString: { $trunc: { $multiply: [{ $divide: ["$fillcount", "$totalDocs"] }, 100] } } },
          "%"
        ]
      }
    }
  }
])

执行后输出结果(与预期完全匹配)

{ "name" : "Raj", "fillcount" : 2, "fillpercentagetototaldocument" : "50%" }
{ "name" : "Rahul", "fillcount" : 4, "fillpercentagetototaldocument" : "66%" }

若需要百分比四舍五入取整,可将代码中的$trunc替换为$round


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.24 22:36:03