我需要替换某些文档中的字符串。我已经用谷歌搜索了这段代码,但不幸的是它并没有改变任何东西。我不确定下面这行的语法:
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 的经验。我只需要替换这个:
{ "source": { "url": "http://aaa/xxx/yyy" } }
与
{ "source": { "url": "http://bbb/xxx/yyy" } }
最佳答案
一般不正确:如果你有字符串 http://aaa/xxx/aaa
(yyy
等于 aaa
)你最终会得到 http://bbb/xxx/bbb
。
但是,如果您对此表示满意,则代码将起作用。
要添加调试信息,请使用 print
函数:
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
函数)
关于javascript - 如何替换Mongo中所有文档中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042450/