如何替换mongodb文件中的子字符串

问题描述 投票:51回答:9

我在表单的集合中有很多mongodb文档:

{
....
"URL":"www.abc.com/helloWorldt/..."
.....
}

我想用helloWorldt替换helloWorld得到:

{
....
"URL":"www.abc.com/helloWorld/..."
.....
}

如何为我的收藏中的所有文件实现此目的?

mongodb mongodb-.net-driver mongo-shell
9个回答
95
投票
db.media.find({mediaContainer:"ContainerS3"}).forEach(function(e,i) {
    e.url=e.url.replace("//a.n.com","//b.n.com");
    db.media.save(e);
});

8
投票

目前,您无法使用字段的值来更新它。因此,您必须遍历文档并使用函数更新每个文档。这里有一个如何做到这一点的例子:MongoDB: Updating documents using data from the same document


5
投票

的NodeJS。使用mongodb package from npm

db.collection('ABC').find({url: /helloWorldt/}).toArray((err, docs) => {
  docs.forEach(doc => {
    let URL = doc.URL.replace('helloWorldt', 'helloWorld');
    db.collection('ABC').updateOne({_id: doc._id}, {URL});
  });
});

5
投票

要替换文档中所有出现的子字符串,请使用:

db.media.find({mediaContainer:"ContainerS3"}).forEach(function(e,i) {
var find = "//a.n.com";
var re = new RegExp(find, 'g');
e.url=e.url.replace(re,"//b.n.com");
db.media.save(e);
});

3
投票

我对所选答案(@ Naveed的答案)的评论格式已经被打乱 - 所以添加这个作为答案。归功于Naveed。

----------------------------------------------------------------------

真棒。我的情况是 - 我有一个数组的字段 - 所以我不得不添加一个额外的循环。

我的查询是:

db.getCollection("profile").find({"photos": {$ne: "" }}).forEach(function(e,i) {
    e.photos.forEach(function(url, j) {
        url = url.replace("http://a.com", "https://dev.a.com");
        e.photos[j] = url;
    });
    db.getCollection("profile").save(e);
    eval(printjson(e));
})

1
投票

启动Mongo 4.2db.collection.update()可以接受聚合管道,最后允许基于另一个字段更新字段:

// { URL: "www.abc.com/helloWorldt/..." }
// { URL: "www.abc.com/HelloWo/..." }
db.collection.update(
  { URL: { $regex: "/helloWorldt/" } },
  [{
    $set: { URL: {
      $concat: [
        { $arrayElemAt: [ { $split: [ "$URL", "/helloWorldt/" ] }, 0 ] },
        "/helloWorld/",
        { $arrayElemAt: [ { $split: [ "$URL", "/helloWorldt/" ] }, 1 ] }
      ]
    }}
  }],
  { multi: true }
)
// { URL: "www.abc.com/helloWorld/..." }
// { URL: "www.abc.com/HelloWo/..." }

这有点冗长,因为还没有合适的字符串$replace运算符。

  • 第一部分{ URL: { $regex: "/helloWorldt/" } }是匹配查询,过滤要更新的文档(hello world错误拼写的文档)。
  • 第二部分[{ $set: { URL: ... } }]是更新聚合管道(注意方括号表示使用聚合管道)。 $set是一个新的聚合运算符,在这种情况下创建/替换字段。由于缺少适当的字符串$concat运算符,使用$split$replace的混合计算奇怪的新值。请注意URL如何根据其自身的值($URL)直接修改。
  • 不要忘记{ multi: true },否则只会更新第一个匹配的文档。

0
投票

现在你可以做到!

我们可以使用Mongo脚本动态操作数据。这个对我有用!

我用这个脚本来纠正我的地址数据。

当前地址示例:“No.12,FIFTH AVENUE”。

我想删除最后一个冗余的逗号,即预期的新地址“”No.12,FIFTH AVENUE“。

var cursor = db.myCollection.find().limit(100);

while (cursor.hasNext()) {
  var currentDocument = cursor.next();

  var address = currentDocument['address'];
  var lastPosition = address.length - 1;

  var lastChar = address.charAt(lastPosition);

  if (lastChar == ",") {

    var newAddress = address.slice(0, lastPosition);


    currentDocument['address'] = newAddress;

    db.localbizs.update({_id: currentDocument._id}, currentDocument);

  }
}

希望这可以帮助!


0
投票

如果您在此处使用答案中的示例并在运行替换脚本时获得“更新的0现有记录”,请检查您的客户端是否已连接到允许您存储/写入更改的主MongoDB节点。


0
投票

Using mongodump,bsondump and mongoimport.

有时mongodb集合可能与嵌套数组/对象等一起变得很复杂,而在它们周围构建循环则相对困难。我的工作有点原始,但在大多数情况下都可以使用,无论集合的复杂程度如何。

1.使用mongodump将集合导出到.bson中

mongodump --db=<db_name> --collection=<products> --out=data/

2.使用bsondump将.bson转换为.json格式

bsondump --outFile products.json data/<db_name>/products.bson

3.用sed(对于linux终端)或任何其他工具替换.json文件中的字符串

sed -i 's/oldstring/newstring/g' products.json

4.使用带有--drop标记的mongoimport导回.json集合,在导入之前它将删除集合

mongoimport --db=<db_name>  --drop --collection products <products.json

或者,您可以在mongoimport和mongodump中使用--uri进行连接

mongodump --uri "mongodb://mongoadmin:[email protected]:27017,10.148.0.8:27017,10.148.0.9:27017/my-dbs?replicaSet=rs0&authSource=admin" --collection=products --out=data/
© www.soinside.com 2019 - 2024. All rights reserved.