MongoDB中移除字符串中间多余空格的技术实现问题
解决MongoDB字符串中间多余空格的问题
$trim只能移除字符串首尾的空白,没法处理中间的连续空格,所以需要结合其他操作符实现需求,以下两种方案都可行:
方案一:用$replaceAll配合正则表达式
通过正则匹配所有连续空白字符,替换为单个空格,再用$trim确保首尾无空格:
db.collection.find( { _id: 3 }, { name: { $trim: { input: { $replaceAll: { input: "$name", find: /\s+/, replacement: " " } } } } } )
方案二:用$split+$filter+$join组合
先把字符串按空格拆分成数组,过滤掉数组里的空元素,再用单个空格重新拼接:
db.collection.find( { _id: 3 }, { name: { $join: { input: { $filter: { input: { $split: ["$name", " "] }, cond: { $ne: ["$$this", ""] } } }, separator: " " } } } )
两种方法都能得到预期结果:{ "_id" : 3, "name" : "Shyam Lingam" }
内容的提问来源于stack exchange,提问作者Radhey Yadav
相关产品推荐
相关产品推荐

