如何替换Mongo中所有文档中的字符串 [英] How to replace string in all documents in 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 experiences 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屋!