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

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

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

相关推荐
DemonAvenger3 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥15 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud19 小时前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术1 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug1 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom1 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*1 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
Slaughter信仰1 天前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十章知识点问答(10题)
java·jvm·数据库
麦兜*1 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring