MongoDB 字段部分内容替换 SQL整理

前言

最近接到一个需求,是需要将一些数据的图片,视频等带http链接的内容替换成https.

以下是我整理的一些SQL, 在此记录,仅供参考
单字段替换

复制代码
db.getCollection('db').find({"cloumn":{$exists:true, $regex:'http:'}}).forEach(function(item){
    var str = item.cloumn;
	var newStr = str.replace('http:', "https:");
	
    db.getCollection("db").update({_id:item._id},{$set:{cloumn: newStr }});  
});

数组字段

第一种只判断字段是否存在

复制代码
db.getCollection('db').find({"cloumn":{$exists:true}}).forEach(function(item){
    var list = item.cloumn;
	for(var i in list) {
	  var str = list[i];
	  var newStr = str.replace('http:', "https:");
	  list[i] = newStr;
	}
	
    db.getCollection("db").update({_id:item._id},{$set:{cloumn: list}});  
});

第二种数组写法,更严谨,判断了字段是不是数组

复制代码
db.getCollection('db').find({"cloumn":{$exists:true}, $where:"Array.isArray(this.cloumn)"}).forEach(function(item){
    var list = item.cloumn;
	for(var i in list) {
	  var str = list[i];
	  // 此处判断是否为null   
	  if(str != null){
	    var newStr = str.replace('http:', "https:");
	    list[i] = newStr;
	  }
	}
	
    db.getCollection('db').update({_id:item._id},{$set:{cloumn: list}});  
});

嵌套数组的话就多次遍历循环替换就好了。

觉得有用的过来看看指导指导,有更好方式的也可以留言,我可以更新进来,一起学习!

相关推荐
程序员夏末2 分钟前
【MySQL | 第一篇】 深入理解三大日志(undo Redo Bin)
数据库·mysql
oradh6 分钟前
Oracle OJVM组件总结
数据库·oracle·ojvm·ojvm补丁
爱写Bug的小孙8 分钟前
多智能体概述
服务器·数据库·ai·oracle·agent·多智能体·agentscop
路由侠内网穿透16 分钟前
本地部署开源零信任网络平台 NetBird 并实现外部访问
运维·服务器·数据库·开源
2301_8042154126 分钟前
使用Python进行量化交易入门
jvm·数据库·python
霑潇雨28 分钟前
题解 | 深入分析各款产品年总销售额与竞品的年度对比
大数据·开发语言·数据库
scofield_gyb44 分钟前
Redis 6.2.7安装配置
前端·数据库·redis
qiumingxun1 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
2401_873544921 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
ruxingli1 小时前
MySQL优化
数据库·mysql