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}});  
});

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

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

相关推荐
睡不醒男孩03082322 分钟前
第一篇:多云与多模态时代的企业级数据库云管理平台(DBaaS)选型指南
数据库·clup·中启乘数
小二·34 分钟前
向量数据库实战
数据库
炘爚1 小时前
Phase 5:MySQL 连接池
数据库·mysql
j_xxx404_1 小时前
MySQL库操作硬核解析:字符集、校验规则、大小写比较、备份恢复与连接排查
运维·服务器·数据库·人工智能·mysql·ai·oracle
minji...2 小时前
MySQL数据库 (五) MySQL表的约束(上),非空约束,默认值约束,零填充约束,主键约束,符合主键
数据库·mysql·表的约束·主键约束·非空约束·复合主键·零填充约束
拾贰_C2 小时前
【python | installation 】python 安装 | Windows | 命令使用
linux·数据库·ubuntu
贺今宵2 小时前
Vue 3 + Capacitor 使用jeep-sqlite,web端使用本地sqlite数据库
前端·数据库·vue.js·sqlite·web
列星随旋2 小时前
MySQL面经整理
数据库·mysql
AllData公司负责人2 小时前
大模型赋能AllData数据中台,系列升级|通过联合智谱大模型与Chat2DB开源项目,建设Text2SQL生产场景全新体验的数据源平台!
数据库·人工智能·text2sql·数据中台·数据源·chat2db·智谱大模型
minji...3 小时前
MySQL数据库 (四) MySQL的数据类型,tinyint,float,decimal,枚举enum和集合set
数据库·mysql·tinyint·enum·decimal·varchar·bit