场景:需要在mongo中,对content表的text(富文本字符串)字段做按条件匹配后的批量修改
方法:
// 注意上面的集合要和下面的集合名称相同
db.test.find(
{
'content': /^.*要替换的字符串.*$/
}
).forEach(
function (item) {
var tmp = String(item.content)
tmp = tmp.replace(/要替换的字符串/g,'替换成字符串')
if (tmp == null){
print(item.content)
}
item.content = tmp ;
// print(tmp)
print(db.test.save(item))
// db.test.save(item)
}
)
示例:
db.content.find(
{
"contentType" : "ARTICLE",
"text" : /^.*https:\/\/www\.nnn\.com\/#\/list\?id=1073&\;channel=1010002001&\;hmnType=0.*$/i,
"authorId" : "100",
// "_id" : ObjectId("123456") 可以使用单条先验证
}
).forEach(
function (item) {
var tmp = String(item.text)
tmp = tmp.replace(/https:\/\/www\.nnn\.com\/#\/list\?id=1073&\;channel=1010002001&\;hmnType=0/g,'https://lll.hhh.com/#/list?id=1073&channel=1010002001')
if (tmp == null){
print("no")
print(item.text)
}else{
print("yes")
// item.text= tmp;
//print(item)
print(item._id)
// db.content.save(item); 注:save方法没执行成功,改用updateOne
db.content.updateOne({_id:item._id},{$set:{'text':tmp}});
}
});
tips:
1.text字段对应的正则表达式,需要特别注意。使用gpt直接问它,让它给你对应的正则
2.注意function中的save方法,我自己处理的时候,修改后没有保存成功,所以改成了updateOne,也可以用replaceOne