How to replace substring in mongodb document

2019-01-04 02:11发布

I have alot of mongodb documents in a collection ABC of the form:

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

I want to replace helloWorldt with helloWorld Final Output:

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

how do i achieve this for all documents in the collection ABC

7条回答
SAY GOODBYE
2楼-- · 2019-01-04 02:35

Just in case if you are using examples from the answers here and get "Updated 0 existing records" when running your replace script, check whether your client is connected to the primary MongoDB node that allows you to store/write changes.

查看更多
Juvenile、少年°
3楼-- · 2019-01-04 02:41

nodejs. Using 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});
  });
});
查看更多
乱世女痞
4楼-- · 2019-01-04 02:41

To replace ALL occurrences of the substring in your document use:

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);
});
查看更多
forever°为你锁心
5楼-- · 2019-01-04 02:44

The formatting of my comment to the selected answer (@Naveed's answer) has got scrambled - so adding this as an answer. All credit goes to Naveed.

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

Just awesome. My case was - I have a field which is an array - so I had to add an extra loop.

My query is:

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));
})
查看更多
放我归山
6楼-- · 2019-01-04 02:45
db.media.find({mediaContainer:"ContainerS3"}).forEach(function(e,i) {
    e.url=e.url.replace("//a.n.com","//b.n.com");
    db.media.save(e);
});
查看更多
姐就是有狂的资本
7楼-- · 2019-01-04 02:45

Now you can do it!

We can use Mongo script to manipulate data on the fly. It works for me!

I use this script to correct my address data.

Example of current address: "No.12, FIFTH AVENUE,".

I want to remove the last redundant comma, the expected new address ""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);

  }
}

Hope this helps!

查看更多
登录 后发表回答