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

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

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

相关推荐
先做个垃圾出来………28 分钟前
SQL的底层逻辑解析
数据库·sql
码不停蹄的玄黓40 分钟前
深入拆解MySQL InnoDB可重复读(RR)隔离级别:MVCC+临键锁如何「锁」住一致性?
数据库·mysql·可重复读
paopaokaka_luck1 小时前
基于SpringBoot+Vue的酒类仓储管理系统
数据库·vue.js·spring boot·后端·小程序
Lx3521 小时前
MySQL物化视图:预计算查询结果的定期刷新
sql·mysql·性能优化
Lx3521 小时前
Mysql死锁日志分析:事务逻辑冲突的排查技巧
sql·mysql·性能优化
薛晓刚2 小时前
哪个领域数据库最难替换?
数据库
RainbowSea2 小时前
14. MySQL 锁的详细说明
java·sql·mysql
芷栀夏2 小时前
基于Anything LLM的本地知识库系统远程访问实现路径
数据库·人工智能
RainbowSea2 小时前
12 MySQL 数据库其它调优策略
java·sql·mysql
软件2053 小时前
【redis使用场景——缓存——数据淘汰策略】
数据库·redis·缓存