如何编写按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
相关产品推荐
相关产品推荐

