最近在用Java处理MongoDB数据以及MySQL数据,昨天想实现的一个小功能,记得之前记在本子里了,但是千里迢迢回去找本子看真的好麻烦,心想还是记在网上,这样以后想知道的时候也方便找。这又是什么鬼前言哈哈。
MongoDB
字段名更新(key值更新)
db.music.updateOne({},{$rename:{'sur':'sure'}}) //只更新匹配到的第一条记录的字段名
db.music.updateMany({},{$rename:{'sur':'sure'}}) //批量更新字段名(字段名由'sur'改为'sure')根据字段值查询
db.music.find({'sure': 5}) //查询sure=5的文档更新字段值
db.music.updateMany({'sure': 5}, {$set: {'sure': 0}}) //将sure=5的文档设其sure=0查询包含某字段(在这里为“歌曲简介”)的文档
db.music.find({'歌曲简介': {$exists:true}}) //统计总数可将find改为count
db.music.find({"音乐风格":{$exists:true}, "歌曲风格":{$exists:false}}) //多字段的存在与否添加/删除字段
db.music.updateOne({}, {$set: {'sure': 0}}) //添加sure字段,其值为0,如果是字符串则加引号
db.music.updateOne({}, {$unset: {'sure': 0}}) //删除sure字段,(sure后的0我还没搞清楚是什么?)对字段“song”进行分组,计算总数,类似MySQL中的count(*)
db.music.aggregate([{$group : {_id : "$song", num_total : {$sum : 1}}}])
db.music.aggregate([{$group : {_id : "$song", num_total : {$sum : 1}}}, {$sort:{"num_total":-1}}])
//对num_total降序排序(1为升序排序)对“actorid”进行分组并统计总数,总数大于1的挑选出来,删除
Var rs=db.actor_copy3.aggregate([{$group:{_id:'$actorid',num_total:{$sum:1}}},{$match:{'num_total':{$gt:1}}}])
while(rs.hasNext()){
var k=rs.next()
var id=k._id
print(id)
db.actor_copy3.deleteMany({'actorid':id})
}
MySQL
统计某些字段不为空的总数
SELECT COUNT(*) FROM actor_copyright
WHERE alias is not NULL and LENGTH(alias) >0
andstatus
=5
and gender is not NULL and gender <> 2
and birthday is not NULL and LENGTH(birthday) >0统计某些字段为空的总数
SELECT COUNT(*) FROM actor_copyright
WHERE (alias is NULL OR LENGTH(alias)=0)
andstatus
=5
and (gender is null OR gender=2)
and (birthday is NULL OR LENGTH(birthday) =0)
ORDER BY countryCode DESC从actor_copy选出来的记录,插入到actor_hs表中
INSERT INTO actor_hs
SELECT * FROM actor_copy
WHEREname
is not NULL and LENGTH(name
) >0
and nameEN is not NULL and LENGTH(nameEN) >0
andstatus
=5
and gender is not NULL and gender <> 2 and gender <>-1
and college is not NULL and LENGTH(college) >0
Java
- 动态生成SQL语句(部分)
List<Object> objParams = new ArrayList<>();
if(mongo_nameEn != null && mongo_nameEn.length() > 0) {
updateSQL += " nameEN=?";
objParams.add(mongo_nameEn);
}
if(mongo_alias != null && mongo_alias.length() > 0) {
if(updateSQL.contains("?")) {
updateSQL += ",alias=?";
}
else {
updateSQL += " alias=?";
}
objParams.add(mongo_alias);
}
updateSQL += " WHERE id=?";
objParams.add(actorId);
num = connect.executeUpdate(updateSQL, objParams);