MongoDB如何投影count前5项 剩余项求和为Other并计算占比
实现方案
直接使用MongoDB聚合管道即可在数据库层完成所有计算,不需要额外业务代码处理,你的集合已经按count字段降序排序,直接运行如下聚合语句即可:
// 替换成你实际的集合名 db.team_collection.aggregate([ { $facet: { // 取排名前5的项 topTeams: [ { $limit: 5 }, { $project: { _id: 0, name: "$_id", count: 1 } } ], // 剩余项求和归为Other otherTeams: [ { $skip: 5 }, { $group: { _id: null, count: { $sum: "$count" } } }, { $project: { _id: 0, name: { $literal: "Other" }, count: 1 } } ] } }, { $project: { mergedList: { $concatArrays: ["$topTeams", "$otherTeams"] }, totalCount: { $sum: { $concatArrays: ["$topTeams.count", "$otherTeams.count"] } } } }, // 计算每一项的占比 { $project: { finalResult: { $map: { input: "$mergedList", as: "item", in: { name: "$$item.name", count: "$$item.count", percent: { $round: [{ $multiply: [{ $divide: ["$$item.count", "$totalCount"] }, 100] }, 0] } } } } } }, { $replaceRoot: { newRoot: "$finalResult" } } ])
- 如果你需要调整百分比的小数精度,修改
$round操作符的第二个参数即可,传入2就会保留两位小数 - 你提供的示例中百分比为示意值,上述语句会按照全量总count计算真实占比,针对你给出的测试数据,运行后返回结果结构如下:
[ {"name":"Team 1", "count":1200, "percent":17}, {"name":"Team 2", "count":1170, "percent":17}, {"name":"Team 3", "count":1006, "percent":14}, {"name":"Team 4", "count":932, "percent":13}, {"name":"Team 5", "count":931, "percent":13}, {"name":"Other", "count":1794, "percent":26} ]
内容的提问来源于stack exchange,提问作者TheStranger
相关产品推荐
相关产品推荐

