MongoDB聚合查询:如何将去重服务值按换行格式输出?
如何在MongoDB中按换行分隔(带空行)输出字段的唯一值
问题场景
现有集合文档结构如下:
_id:1 service: "microservice-1" domain: "retail" _id:2 service: "microservice-2" domain: "insurance" _id:3 service: "microservice-1" domain: "retail" _id:4 service: "microservice-3" domain: "communications" _id:5 service: "microservice-2" domain: "insurance"
使用db.collections.aggregate([{$group: {_id:null, listOfService: {"$addToSet" : "$service"}}}}])得到的是数组格式结果,需要转为每个值单独一行、中间带空行的输出。
解决方案1:Mongo Shell 客户端处理(最直观)
先通过聚合获取唯一的service值,再用Shell的forEach方法格式化输出:
// 聚合获取排序后的唯一service值 db.collections.aggregate([ {$group: {_id: "$service"}}, // 直接按service分组,自动去重 {$sort: {_id: 1}} // 可选:按service名称排序 ]).forEach(doc => { print(doc._id); // 打印当前service值 print(); // 打印空行分隔 })
执行后会直接输出符合要求的格式:
microservice-1 microservice-2 microservice-3
解决方案2:聚合管道内生成格式化字符串
如果需要直接在聚合结果中得到带换行的字符串,可使用$reduce和$concat拼接:
db.collections.aggregate([ {$group: {_id: null, services: {$addToSet: "$service"}}}, {$sort: {services: 1}}, // 可选排序 {$project: { _id: 0, formatted_output: { $reduce: { input: "$services", initialValue: "", in: {$concat: ["$$value", "$$this", "\n\n"]} } } }} ])
结果中的formatted_output字段就是带换行和空行的目标字符串。
为什么之前用$unwind没成功?
你之前的聚合是将所有唯一值放到一个数组中,$unwind后会生成多个包含单个service值的文档,但Mongo Shell默认会输出完整的文档结构(如{ "_id" : null, "listOfService" : "microservice-1" }),而非仅字段值。需要配合$project只保留目标字段,再用forEach打印,或者直接用上面的方案1更高效。
内容的提问来源于stack exchange,提问作者Naina
相关产品推荐
相关产品推荐

