【问题标题】:remove whitespace which are in between String in Mongodb删除 Mongodb 中 String 之间的空格
【发布时间】:2023-02-24 13:07:54
【问题描述】:

对于本文档:{ "_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 之间仍然存在不应该出现的空白。

【问题讨论】:

  • 为什么 Shyam 和 Lingam 之间的空间不会被移除?
  • 嗨@ray,是的,预计不会被删除
  • 你的标题很混乱。 $trim 怎么不工作了?
  • trim 正在工作,但它删除了左右空格,但我想删除“Shyam”和“Lingam”之间的空格。
  • 所以中间的空格应该删除还是不删除???您的预期行为不断变化!你应该edit你的问题和预期的输出。

标签: string mongodb trim


【解决方案1】:

这个查询可能看起来很复杂。

  1. $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"
                ]
              }
            }
          }
        }
      }
    })
    

    Demo @ Mongo Playground

【讨论】:

  • 嗨@Youg Shun,是否没有特定的运算符可用于删除字符串中的空格,如$trim?我们可以只使用一个可以给出相同结果的运算符,而不是使用许多运算符来获得这个结果
  • $trim 只支持去掉开头和结尾的空格。我认为 MongoDB 中没有任何运营商支持您的要求。因此,不得不做一些“肮脏”的工作。
  • 谢谢永顺,那我就用这个逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
相关资源
最近更新 更多