对于本文档:
{ "_id" : 3, "name" : " Shyam Lingam " }
预期: 在检索 _id = 3 时结果应如下所示:
{ "_id" : 3, "name" : "Shyam Lingam" }
我试过这个:
db.collection.find({_id:3},{name:{$trim:{input:"$name"}}})
{ "_id" : 3, "name" : "Shyam Lingam" }
但 Shyam 和 Lingam 之间仍然存在不应该出现的空白。
这个查询可能看起来很复杂。
$trim
- 在开始和结束处修剪1.1的值。
1.1。
$reduce
- 将数组转换为字符串。
1.1.1。
input
- 按空格拆分 name
并过滤不是空格的单词。
1.1.2。
initialValue
- 将初始值设置为空字符串。
1.1.3。
in
- 使用 $concat
,将所有元素组合成一个以 ' ' 作为分隔符的字符串。
db.collection.find({
_id: 3
},
{
name: {
$trim: {
input: {
$reduce: {
input: {
$filter: {
input: {
$split: [
"$name",
" "
]
},
cond: {
$ne: [
"$$this",
""
]
}
}
},
initialValue: "",
in: {
$concat: [
"$$value",
" ",
"$$this"
]
}
}
}
}
}
})
试试这个,我希望它能奏效
db.collection.update(
{ "_id": 3 },
{ "$set": { "name": { "$trim": { "input": "$name" } } } }
)
更新后输出为:
{ "_id" : 3, "name" : "Shyam Lingam" }