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

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

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

相关推荐
zbguolei20 小时前
上传 Excel 文件进行数据库比对--增加导出功能
数据库·excel
amao998820 小时前
数据库原理与技术 - 3-7 视图和索引 View& Index
数据库·sql·oracle
酸菜牛肉汤面20 小时前
30、大表数据查询,怎么优化
数据库
KG_LLM图谱增强大模型20 小时前
企业级实用本体论的实践指南(2/4):Palantir Foundry如何将组织数据映射到本体概念及关键设计考量
数据库·人工智能
陌路2021 小时前
redis智能缓存策略--思想
数据库·redis·缓存
计算机毕设VX:Fegn089521 小时前
计算机毕业设计|基于springboot + vue出行旅游安排系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·课程设计
一只大黄猫21 小时前
【数据库-入门3】基本概念
数据库
@海~涛21 小时前
AOSP源码下载与编译
android·数据库·缓存·安卓·安全架构
五阿哥永琪21 小时前
MySQL 如何定位&分析慢查询?
android·数据库·mysql
柒.梧.21 小时前
从原理到实战:Spring AOP全解析
数据库·sql