MongoDB使用正则匹配、修改内容

文档结构:

{
    "_id": ObjectId("9683839960905afb31542868"),
    "articleDetail": "<p><strong>尊敬的用户:</strong></p>\n<p>&nbsp; &nbsp; &nbsp; 根据XXX通知精神,通知如下图:</p>\n<img src='https://www.oss.main.com/upload/file/20211221/D1E15045BA504614BCB9CF6D2DBBF147.png' />\n<p style=\"text-align: right;\"><strong>&nbsp;特此公告!</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);
                }
            );
        }
    }
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值