我只需要更改字符串中包含“”的字符串

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

我需要更改属性的字符串。我只需要更改上面有空格的即可。

错误网址: “url.com 虚拟/”

好网址: “url.com/dummy/”

实际:

   {  
     test: "test1",  
     Attach: [{  
        Type: "img",  
        Url: "https://url.com dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com/dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com/dummy/"
     }] 
   }  

预期:

   {  
     test: "test1",  
     Attach: [{  
        Type: "img",  
        Url: "https://url.com/dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com/dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com/dummy/"
     },
     {  
        Type: "img",
        Url: "https://url.com/dummy/"
     }] 
   }  

如您所见,我需要更改的属性位于数组内部。

我需要一个脚本来在整个集合中进行验证。

谢谢您的帮助!

mongodb mongodb-query
1个回答
0
投票

您可以在聚合管道中使用

$regex
来查找有空格的文档。然后使用
$replaceAll
将空格替换为斜杠。最后
$merge
将结果返回到原始集合。

db.collection.aggregate([
  {
    $match: {
      // find documents with space inside
      "Attach.Url": {
        $regex: " "
      }
    }
  },
  {
    "$addFields": {
      "Attach": {
        "$map": {
          "input": "$Attach",
          "as": "a",
          "in": {
            Type: "$$a.Type",
            Url: {
              // replace space by slash
              "$replaceAll": {
                "input": "$$a.Url",
                "find": " ",
                "replacement": "/"
              }
            }
          }
        }
      }
    }
  },
  {
    // merge back to original collection
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])

这里是Mongo游乐场供您参考。

© www.soinside.com 2019 - 2024. All rights reserved.