日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

MongoDB使用正則匹配、修改內(nèi)容

作者:csdn-CODER! 更新時間: 2022-07-11 編程語言

文檔結(jié)構(gòu):

{
    "_id": ObjectId("9683839960905afb31542868"),
    "articleDetail": "<p><strong>尊敬的用戶:</strong></p>\n<p>&nbsp; &nbsp; &nbsp; 根據(jù)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": "這是一個標(biāo)題",
    "type": NumberInt("0"),
    "updateTime": NumberLong("1636568109000")
}

MongoDB更新語句:

// 功能描述:將數(shù)據(jù)庫中的URL進行替換
var result= "https://www.baidu.com";
// 文章修改
// 這里的find查詢出了所有文檔,實際運用中為了效率可以過濾一部分內(nèi)容
db.article.find().forEach(
    function(item) {
        // 修改內(nèi)容里的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}});	
        }
        // 遍歷圖片數(shù)組,進行修改(數(shù)組遍歷修改)
        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);
                    // 拼接數(shù)組下標(biāo)
					var tmp = "images."+index+".url";
					// 構(gòu)建一個JSON對象,傳入update
					tmp = JSON.parse('{"$set":{"'+ tmp + '" : "'+url+'"}}');	
					db.article.update({"_id":item._id}, tmp);
                }
            );
        }
    }
);

原文鏈接:https://blog.csdn.net/a272265225/article/details/122314405

欄目分類
最近更新