文档结构:
{
"_id": ObjectId("9683839960905afb31542868"),
"articleDetail": "<p><strong>尊敬的用户:</strong></p>\n<p> 根据XXX通知精神,通知如下图:</p>\n<img src='https://www.oss.main.com/upload/file/20211221/D1E15045BA504614BCB9CF6D2DBBF147.png' />\n<p style=\"text-align: right;\"><strong> 特此公告!</strong></p>",
"author": "user001",
"categoryId": "1",
"clickCount": NumberLong("1"),
"enable": NumberInt("1"),
"files": [ ],
"images": [
{
"urlType": NumberInt("0"),
"url": "https://www.oss.main.com/upload/file/20211221/D1E15045BA504614BCB9CF6D2DBBF147.png",
"name": "img001.png",
"suffix": "png"
},
{
"urlType": NumberInt("0"),
"url": "https://www.oss.main.com/upload/file/20211221/D1E15045BA504614BCB9CF6D2DBBF147.png",
"name": "img002.png",
"suffix": "png"
}
],
"isDelete": NumberInt("0"),
"link": null,
"sort": NumberInt("0"),
"source": "无",
"summary": "摘要",
"title": "这是一个标题",
"type": NumberInt("0"),
"updateTime": NumberLong("1636568109000")
}
MongoDB更新语句:
// 功能描述:将数据库中的URL进行替换
var result= "https://www.baidu.com";
// 文章修改
// 这里的find查询出了所有文档,实际运用中为了效率可以过滤一部分内容
db.article.find().forEach(
function(item) {
// 修改内容里的URL(单个字段)
var detail = item.articleDetail;
if (detail != null) {
print("detail start change:" + item._id);
detail = detail.toString().replace(/http[s]*:\/\/[^\/]*/gi, result);
// 使用update进行修改,可兼容MongoDB 3.x
db.article.update({"_id":item._id}, {$set:{"articleDetail": detail}});
}
// 遍历图片数组,进行修改(数组遍历修改)
if (item.images != null) {
item.images.forEach(
function(arr, index) {
var url = item.images[index].url.toString();
print('old:' + url);
url = url.replace(/http[s]*:\/\/[^\/]*/gi, result);
print("new:" + url);
// 拼接数组下标
var tmp = "images."+index+".url";
// 构建一个JSON对象,传入update
tmp = JSON.parse('{"$set":{"'+ tmp + '" : "'+url+'"}}');
db.article.update({"_id":item._id}, tmp);
}
);
}
}
);