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

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

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

相关推荐
ClouGence11 分钟前
当 AI 开始直接操作数据库,传统数据库管理工具还有必要吗?
数据库·后端·agent
Hugh-Yu-1301231 小时前
zhangxuefeng-skill配置教程
数据库
布莱克6051 小时前
理解B+树:原理、特性与应用场景
数据结构·数据库·mysql
冰暮流星1 小时前
mysql之排序查询
数据库·mysql
7177771 小时前
让权限治理成为可复制资产:Gitee Team 空间配置方案与安全级别落地详解
数据库·gitee
今天AI了吗1 小时前
Agent & AI 名词大扫盲
数据库·人工智能·python·sql·rust
葡萄城技术团队1 小时前
告别宽表拖拽:SpreadJS 如何让 Web 表格承接 Excel 操作习惯
数据库·html·excel
2603_966437262 小时前
格式化之后数据还能恢复吗?说清恢复条件
linux·运维·数据库
倔强的石头1063 小时前
时序数据库的难题不只在写入速度
数据库·时序数据库
IT小白杨3 小时前
海外业务账号安全保障:主流浏览器产品底层机制对比
数据库·python·安全·自动化·安全架构·指纹浏览器