首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何替换短语mongodb的多次出现

如何替换短语mongodb的多次出现
EN

Stack Overflow用户
提问于 2020-02-24 23:54:45
回答 1查看 286关注 0票数 1

我试图在同一个字段中替换同一短语的多次出现。

下面是字段“imageUrl”内容的一个示例:

"imageUrl“:"2000x.png?v=1576212956\n \n 2000x.png?v=1576212956\n \n”

我目前的公式:

代码语言:javascript
复制
  {
      $match: {
           imageUrl: { $regex: "_2000x" },
           brand: "Goat The Label"
      }
  },
  { 
      $addFields: { 
          imageUrl: { $split: [ "$imageUrl", "_2000x" ] } 
      } 
  },
  { 
      $addFields: { 
          imageUrl: { 
              $concat: [ 
                        { $arrayElemAt: [ "$imageUrl", 0 ] }, 
                        "_850x", 
                        { $arrayElemAt: [ "$imageUrl", 1 ] }
              ] 
          }
      }
 }]).forEach( doc => db.product.updateOne( { _id: doc._id }, { $set: { imageUrl: doc.imageUrl } } ) )

将下列内容转换为:

"imageUrl“:"850x.png?v=1576212956\n \n \n”‘’

然而,我希望输出是:

"imageUrl“:"850x.png?v=1576212956\n \n 850x.png?v=1576212956\n \n”

这两个urls仍然存在并适应于_850x维度。

注:字段输入可能超过一个(可能包含2-7)。

预先感谢您的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-25 01:34:38

$reduce更适合您的用例:

伪码

代码语言:javascript
复制
value = url.split("_2000x")[0]
for (item: url.split("_2000x")[1:])
    value += "_850x" + item
代码语言:javascript
复制
db.collection.aggregate([
  {
    $match: {
      imageUrl: {
        $regex: "_2000x"
      },
      brand: "Goat The Label"
    }
  },
  {
    $addFields: {
      imageUrl: {
        $reduce: {
          input: {
            $slice: [
              {
                $split: [
                  "$imageUrl",
                  "_2000x"
                ]
              },
              1,
              {
                $size: {
                  $split: [
                    "$imageUrl",
                    "_2000x"
                  ]
                }
              }
            ]
          },
          initialValue: {
            $arrayElemAt: [
              {
                $split: [
                  "$imageUrl",
                  "_2000x"
                ]
              },
              0
            ]
          },
          in: {
            $concat: [
              "$$value",
              "_850x",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

MongoPlayground

编辑:通过Bash执行的

窗口:

使用以下内容创建temp.js文件:

代码语言:javascript
复制
db.collection.aggregate(...).forEach(...)

使用以下内容创建temp.bat文件:

代码语言:javascript
复制
@echo off

path/to/mongo.exe --uri put_here_mongodb+srv temp.js

现在运行:temp.bat

Unix:

使用以下内容创建temp.js文件:

代码语言:javascript
复制
db.collection.aggregate(...).forEach(...)

使用以下内容创建temp.bat文件:

代码语言:javascript
复制
#!/bin/bash

path/to/mongo --uri put_here_mongodb+srv temp.js

授予执行权限:chmod u+x temp.sh

现在运行:./temp.sh

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60385674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档