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

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

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

相关推荐
陌上丨9 小时前
Redis的Key和Value的设计原则有哪些?
数据库·redis·缓存
AI_56789 小时前
AWS EC2新手入门:6步带你从零启动实例
大数据·数据库·人工智能·机器学习·aws
ccecw10 小时前
Mysql ONLY_FULL_GROUP_BY模式详解、group by非查询字段报错
数据库·mysql
JH307310 小时前
达梦数据库与MySQL的核心差异解析:从特性到实践
数据库·mysql
数据知道10 小时前
PostgreSQL 核心原理:如何利用多核 CPU 加速大数据量扫描(并行查询)
数据库·postgresql
麦聪聊数据11 小时前
Web 原生架构如何重塑企业级数据库协作流?
数据库·sql·低代码·架构
未来之窗软件服务11 小时前
数据库优化提速(四)新加坡房产系统开发数据库表结构—仙盟创梦IDE
数据库·数据库优化·计算机软考
Goat恶霸詹姆斯13 小时前
mysql常用语句
数据库·mysql·oracle
大模型玩家七七13 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
曾经的三心草13 小时前
redis-9-哨兵
数据库·redis·bootstrap