英文:
remove whitespace which are in between String in Mongodb
问题
期望的结果: 在检索 _id = 3 时,结果应该如下所示:
{ "_id" : 3, "name" : "Shyam Lingam" }
我尝试过的: db.collection.find({_id:3},{name:{$trim:{input:"$name"}}})
{ "_id" : 3, "name" : "Shyam Lingam" }
但仍然存在 Shyam 和 Lingam 之间的空格,这不应该出现。
英文:
For this document: { "_id" : 3, "name" : " Shyam Lingam " }
Expected: while retrieving _id = 3 then result should come like below:
{ "_id" : 3, "name" : "Shyam Lingam" }
I tried this: db.collection.find({_id:3},{name:{$trim:{input:"$name"}}})
{ "_id" : 3, "name" : "Shyam Lingam" }
but still whitespace between Shyam and Lingam is there which should not come.
答案1
得分: 0
以下是代码的翻译部分:
-
$trim
- 在开头和结尾修整值 1.1。1.1.
$reduce
- 将数组转换为字符串。1.1.1.
input
- 通过空格拆分name
并过滤不是空格的单词。1.1.2.
initialValue
- 将初始值设置为空字符串。1.1.3.
in
- 使用$concat
,将所有元素合并成一个以空格为分隔符的字符串。
英文:
This query may look complex.
-
$trim
- Trim the value of 1.1 at the beginning and end.1.1.
$reduce
- Transform array to string.1.1.1.
input
- Splitname
by space and filter the word which is not space.1.1.2.
initialValue
- Set the initial value as an empty string.1.1.3.
in
- With$concat
, combine all the elements into a string with ' ' as the delimiter.
db.collection.find({
_id: 3
},
{
name: {
$trim: {
input: {
$reduce: {
input: {
$filter: {
input: {
$split: [
"$name",
" "
]
},
cond: {
$ne: [
"$$this",
""
]
}
}
},
initialValue: "",
in: {
$concat: [
"$$value",
" ",
"$$this"
]
}
}
}
}
}
})
答案2
得分: 0
试试这个,我希望它应该可以工作
db.collection.update(
{ "_id": 3 },
{ "$set": { "name": { "$trim": { "input": "$name" } } } }
)
更新后的输出是:
{ "_id": 3, "name": "Shyam Lingam" }
英文:
Try this i hope it should be work
db.collection.update(
{ "_id": 3 },
{ "$set": { "name": { "$trim": { "input": "$name" } } } }
)
After update output is:
{ "_id" : 3, "name" : "Shyam Lingam" }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论