删除 Mongodb 中字符串之间的空格

问题描述 投票:0回答:2

对于本文档:

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

string mongodb trim
2个回答
0
投票

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

  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


0
投票

试试这个,我希望它能奏效

db.collection.update(
  { "_id": 3 },
  { "$set": { "name": { "$trim": { "input": "$name" } } } }
)

更新后输出为:

{ "_id" : 3, "name" : "Shyam Lingam" }
© www.soinside.com 2019 - 2024. All rights reserved.