删除MongoDB中字符串之间的空白。

huangapple go评论59阅读模式
英文:

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

以下是代码的翻译部分:

  1. $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.

  1. $trim - Trim the value of 1.1 at the beginning and end.

    1.1. $reduce - Transform array to string.

    1.1.1. input - Split name 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"
            ]
          }
        }
      }
    }
  }
})

Demo @ Mongo Playground

答案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" }

huangapple
  • 本文由 发表于 2023年2月24日 12:14:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定