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

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

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

相关推荐
晚风_END1 小时前
Linux|操作系统|最新版openzfs编译记录
linux·运维·服务器·数据库·spring·中间件·个人开发
dLYG DUMS2 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
数据库·mysql
kumat3 小时前
分享-搭建个人系统 MySelfSys
sql·系统
苍煜3 小时前
MySQL分库分表和ES到底怎么选?
数据库·mysql·elasticsearch
茉莉玫瑰花茶3 小时前
Qt 信号与槽 [ 1 ]
开发语言·数据库·qt
czlczl200209253 小时前
松散索引扫描/跳跃索引扫描
数据库·mysql·性能优化
星马梦缘5 小时前
数据库作战记录 实验7、8
数据库·sql·oracle
安逸sgr5 小时前
Hermes Agent + Obsidian 打造第二大脑(六):分层记忆系统的设计逻辑——L0/L1/L2/L3 四层记忆详解
数据库·agent·知识库·hermes·hermesagent
苍煜6 小时前
一篇讲懂分库分表:概念、spirngboot实战
数据库·oracle
梦想画家6 小时前
PostgreSQL 物化视图实战:从数据固化到智能刷新的全链路指南
数据库·postgresql·物化视图