如何在Mongo中替换所有文档中的字符串 [英] How to replace string in all documents in Mongo

查看:28
本文介绍了如何在Mongo中替换所有文档中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要替换某些文档中的字符串.我用谷歌搜索了这段代码,但不幸的是它没有改变任何东西.我不确定下面一行的语法:

I need to replace a string in certain documents. I have googled this code, but it unfortunately does not change anything. I am not sure about the syntax on the line bellow:

pulpdb = db.getSisterDB("pulp_database");
var cursor = pulpdb.repos.find();
while (cursor.hasNext()) {
  var x = cursor.next();
  x['source']['url'].replace('aaa', 'bbb'); // is this correct?
  db.foo.update({_id : x._id}, x);
}

我想添加一些调试打印来查看值是什么,但我没有使用 MongoDB Shell 的经验.我只需要替换这个:

I would like to add some debug prints to see what the value is, but I have no experience with MongoDB Shell. I just need to replace this:

{ "source": { "url": "http://aaa/xxx/yyy" } }

{ "source": { "url": "http://bbb/xxx/yyy" } }

推荐答案

一般不正确:如果你有字符串 http://aaa/xxx/aaa (yyy 等于 aaa) 你最终会得到 http://bbb/xxx/bbb.但是如果你同意这个,代码就可以工作了.

It doesn't correct generally: if you have string http://aaa/xxx/aaa (yyy equals to aaa) you'll end up with http://bbb/xxx/bbb. But if you ok with this, code will work.

使用print函数添加调试信息:

To add debug info use print function:

var cursor = db.test.find();
while (cursor.hasNext()) {
  var x = cursor.next();
  print("Before: "+x['source']['url']);
  x['source']['url'] = x['source']['url'].replace('aaa', 'bbb');
  print("After: "+x['source']['url']);
  db.test.update({_id : x._id}, x);
}

(顺便说一句,如果你想打印对象,还有printjson函数)

这篇关于如何在Mongo中替换所有文档中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆