MongoDB分组实现按type求和total并输出去重后逗号分隔value值
实现思路
- 第一阶段用
$group按type字段分组:- 通过
$sum累加同组所有total字段值得到总和 - 通过
$addToSet收集同组value字段的唯一值,自动去重后存为数组
- 通过
- 第二阶段用
$project调整输出格式:- 保留
type、求和后的total字段 - 通过
$join操作符将唯一值数组用逗号拼接为字符串
- 保留
可运行聚合查询代码
(适用MongoDB 4.4及以上版本,将代码中的your_collection替换为实际集合名即可)
db.your_collection.aggregate([ { $group: { _id: "$type", total: { $sum: "$total" }, uniqueValues: { $addToSet: "$value" } } }, { $project: { _id: 0, type: "$_id", total: 1, value: { $join: [ "$uniqueValues", "," ] } } } ])
低版本MongoDB兼容方案(4.4以下无$join的场景)
把$project阶段的$join替换为$reduce实现拼接即可:
{ $project: { _id: 0, type: "$_id", total: 1, value: { $reduce: { input: "$uniqueValues", initialValue: "", in: { $cond: [ { $eq: [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", ",", "$$this" ] } ] } } } } }
内容的提问来源于stack exchange,提问作者user12883228
相关产品推荐
相关产品推荐

