MongoDB 常用脚本

MongoDB

常用命令

-- 创建集合
db.createCollection('mytestcopy');

-- 修改集合字段名称
-- {}:是过滤条件。(更新哪些文档);
-- {’$rename’: {‘raw_field’: 'new_field}}:是更新操作;
-- fasle:若根据该过滤条件无法找到匹配的文档时,不插入该文档。
-- true:更新多条(但是我在用这个的时候不太好使,还是用的updateMany来更新的多条)。
db.Test.updateMany({}, {'$rename': {'raw_field': 'new_field'}}, false, true)


db.getCollection('集合名').update({}, {$rename : {"修改前字段名" : "修改后字段名"}}, {multi:true})

-- 集合中添加String类型的字段字段
 db.table.update({}, {$set: {content:""}}, {multi: true})

-- 删除集合中的字段
db.XXX.update({
    "字段名": {
        "$exists": true
    }
}, {
    "$unset": {
        "字段名":null
    }
}, {
    multi: true
});



-- 插入数据脚本
var tags = ["nosql","mongodb","document","developer","popular"]; 
var types = ["technology","sociality","travel","novel","literature"]; 
var books=[]; for(var i=0;i<50;i++){ var typeIdx = Math.floor(Math.random()*types.length); 
var tagIdx = Math.floor(Math.random()*tags.length); 
var favCount = Math.floor(Math.random()*100); 
var book = { title: "book-"+i, type: types[typeIdx], tag: tags[tagIdx], favCount: favCount, author: "xxx"+i };
books.push(book) }db.mytest.insertMany(books);

-- 查询集合中的全部元素
db.mytest.find({});

-- 查询集合中的指定元素
db.books.find({_id:ObjectId("61caa09ee0782536660494d9")});

-- 删除集合中多有的document
db.XXX.deleteMany({});

-- 直接删除集合
db.XXX.drop();

-- 删除数据
db.XXX.remove({_id:ObjectId("6242df12f9506c38a8180448")})

-- 插入数据
db.getCollection("XXX").insert( {
    _id: ObjectId("6242df12f9506c38a8180448"),
    name: "项目"
});

-- 备份集合
db.XXX.find().forEach(function(x){db.XXX.insert(x)});

-- 将集合中的某个字段值赋值给另一个字段
db.XXX.find().forEach(function(x) {
    db.XXX.update({
        _id: x._id
    }, {
        $set: {
            字段名: x.字段名
        }}, false, true
    )
});

-- 待验证
-- mongodb中直接根据某个字段更新另外一个字段值
--表:tblCard 要更新的字段:tPAFlow 值字段: pFlow 过滤 条件:{"lCycle":2}
db.tblCard.find({"lCycle":2}).forEach(

   function(item){                 
       db.tblCard.update({"_id":item._id},{"$set":{"tPAFlow":item.pFlow}},false,true) 
    }
);

-- 批量更新嵌套数组内的组的字段值为常量    第三个参数标识是否启用upsert,第四个参数表示是否更新多条
db.XXX.updateMany({'对象名.属性名': 'a'}, {$set: {'对象名.$.属性名': 'b'}}, false, true);



-- 更新指定内嵌文档
db.getCollection("XXX").update({_id:ObjectId("123")},{$set:{"XXX": ["123"]}})

-- 1.统计
db.XXX.find({ $and : [{"字段A" : null}, ] }).count();
-- 2.更新
db.XXX.updateMany({ $and : [{"字段A" : null}] }, {$set: {'字段A': 'A'}}, false, true);


-- 更新XXX表字段名称
db.XXX.updateMany({}, {'$rename': {'raw_field': 'new_field'}}, false, true)


-- 切换到源库
use db_source; # db_source = 需要拷贝数据的库
var test_copy = db_source.table.find(); # table = 要迁移的表
use db_target; # db_target = 拷贝的目标库
test_copy.forEach(function(d){db.coll_target.insert(d)}); # coll_target = 目标表

db.XXX.aggregate([
{$group:{_id:{字段名A:"$字段名A",字段名B:"$字段名B"},count: { $sum: 1 }}},
{ $match: { count: { $gt: 1 } } }
])



-- 单一字段分组
# 比如对比sql:select userid from testgroup by userid
db.test.aggregate({"$group":{"_id":"$userid"}} )

-- 多字段分组
-- _id为固定写法,userid与articleid为分组字段,多字段时需要设置一个别名
# 比如对比sql:select userid,articleid from testgroup by userid,articleid
db.test.aggregate({"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}})


-- 条件匹配分组
-- $match表示匹配条件,在group前表示where,在后表示having,userid为分组字段
# 比如对比sql:select userid from testwhere userid in("1","2")  group by userid
db.test.aggregate(
    {"$match":{"userid":{"$in":["1","2"]}}},
    {"$group":{"_id":"$userid"}}
)
或者
# 比如对比sql:select userid,articleid from test where userid in("1","2")  group by userid
db.test.aggregate(
    {"$match":{"userid":{"$in":["1","2"]}}},
    {"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}}
)
或者having聚合查询
# 比如:select userid,avg(price) as avg from test where userid >'10' group by userid having avg>35
db.test.aggregate(
    {"$match":{"userid":{"$gt":"10"}}},
    {"$group":{"_id":"$userid",'avg':{"$avg":"$price"}}},
    {"$match":{"avg":{"$gt":35}}}
)


-- 处理XXX表重复脏数据
db.XXX.aggregate(
	{"$group":{"_id":{"字段A":"$字段A","字段B":"$字段B"},字段A:{"$first":"$字段A"},字段B:{"$first":"$字段B"},count: { $sum: 1 }}},
	{ "$match": { count: { $gt: 1 } } },
	{"$project" : {_id:0}}
).forEach(function(item) {
		db.XXX.updateMany({ $and : [ {"字段A" : item.字段A},{"字段B" : item.字段B}]}, {$set: {'enabled': true}}, false, true);
});


// 级联
db.XXXX.aggregate([
{
        $match: {
            _id: ObjectId("123")
        }
    },
    {
        
        $project:{
            "id":{
                "$convert":{
										"input":"$_id",
										"to":"string"
								}
            }
        }
    },
    {
        $lookup: {
            from: "XXXX",
            localField: "id",
            foreignField: "parentId",
            as: "childer"
        }
    }
])



-- 删除数组字段中指定的元素
db.XXXX.updateMany({"数组字段名":{"$in":[null]}}, {'$pull': {'数组字段名': null}}, false, true);

db.XXX.find({
    "$and": [{
        "字段名": "A"
    }]
}).forEach(function(item) {
    db.XXX.updateMany({
        "$and": [{
            "字段名": "ADMIN"
        }, {
            "字段名":{$in:item.ids}
        }]
    }, {
        $addToSet: { "ids": { $each: item.ids } }
    }, false, true);
});

// 功能描述:将数据库中的URL进行替换
var result= "https://www.baidu.com";
// 文章修改
// 这里的find查询出了所有文档,实际运用中为了效率可以过滤一部分内容
db.article.find().forEach(
    function(item) {
        // 修改内容里的URL(单个字段)
        var detail = item.articleDetail;
        if (detail != null) {
			print("detail start change:" + item._id);
            detail = detail.toString().replace(/http[s]*:\/\/[^\/]*/gi, result);
            // 使用update进行修改,可兼容MongoDB 3.x
			db.article.update({"_id":item._id}, {$set:{"articleDetail": detail}});	
        }
        // 遍历图片数组,进行修改(数组遍历修改)
        if (item.images != null) {
            item.images.forEach(
                function(arr, index) {
                    var url = item.images[index].url.toString();
                    print('old:' + url);
                    url = url.replace(/http[s]*:\/\/[^\/]*/gi, result);
                    print("new:" + url);
                    // 拼接数组下标
					var tmp = "images."+index+".url";
					// 构建一个JSON对象,传入update
					tmp = JSON.parse('{"$set":{"'+ tmp + '" : "'+url+'"}}');	
					db.article.update({"_id":item._id}, tmp);
                }
            );
        }
    }
);

-- 正则刷数据
db.XXXX.find({"phone":/^\+|-/});
db.XXXX.find({
    "deletedFlag": false,
    "phone":/^\+|-/
}).forEach(
    function(item) {
		var phone = item.phone.toString().replace(/^\+*[-]*|-*/, "");
		print(phone);
		item.phone = phone;
		db.XXXX.save(item);
		}
)

db.XXX.aggregate([
    {
        "$match": {
            "type": "A",
            "deletedFlag": false
        }
    },
    {
        $group: {
            "_id": {
                "字段名": "$字段名",
                "字段名": "$字段名"
            },
            count: {
                $sum: 1
            },
						dups:{$addToSet:'$_id'}
        }
    },
   
   
    {
        $match: {
            count: {
                $gt: 1
            }
        }
    }
]).forEach(function(it){
         it.dups.shift();
         db.XXX.remove({_id: {$in: it.dups}});

    });

db.XXX.updateMany( {_id:ObjectId("123")}, {"$set": {"enabled":true}}, false, true)

--  统计
db.getCollection("XXX").aggregate([{
    "$match": {
        "$and": [{
            "$and": [{
                "enabled": false
            }]
        }]
    }
}, {
    "$unwind": {
        "path": "$字段名",
        "preserveNullAndEmptyArrays": true
    }
}, {
    "$group": {
        "_id": {
            "字段名": "$字段名",
            "字段名": "$字段名"
        },
        "字段名": {
            "$sum": "$字段名"
        }
    }
}, {
    "$group": {
        "_id": "$_id.字段名",
        "别名": {
            "$push": {
                "别名": "$_id.字段名",
                "别名": "$字段名"
            }
        }
    }
}, {
    "$sort": {
        "_id": 1
    }
}]);


-- 根据某一个字段,删除重复数据
db.XXX.aggregate([

  { $group: { _id: { 字段名: "$字段名" }, uniqueIds: { $addToSet: "$_id" }, count: { $sum: 1 } } },
  { $match: { count: { $gt: 1 } } },
  {
    $project: {
      _id: { $arrayElemAt: ["$uniqueIds", 0] },
      remainingIds: { $slice: ["$uniqueIds", 1, { $size: "$uniqueIds" }] }
    }
  }
]).forEach(function(doc) {
  db.XXX.deleteMany({ _id: { $in: doc.remainingIds } });
});







	 




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是 MongoDB 数据库备份和还原的脚本示例: 备份脚本: ``` #!/bin/bash # MongoDB backup script # MongoDB credentials user="username" password="password" host="localhost" port="27017" db_name="database_name" # Other options backup_path="/path/to/backup/folder" date=$(date +"%d-%b-%Y") # Backup filename filename="$db_name-$date.tar.gz" # Backup command mongodump --host=$host --port=$port --username=$user --password=$password --db=$db_name --out=$backup_path/$db_name-$date # Compression command tar -zcvf $backup_path/$filename $backup_path/$db_name-$date # Remove uncompressed folder rm -rf $backup_path/$db_name-$date ``` 在备份脚本中,您需要将 `username`、`password`、`host`、`port` 和 `database_name` 替换为您的 MongoDB 访问凭据和数据库名称。`backup_path` 变量指定备份文件应该存储在哪个文件夹中,`date` 变量用于生成备份文件名。 在备份期间,`mongodump` 命令将备份文件存储在指定的文件夹中。然后,使用 `tar` 命令将文件夹压缩为 `.tar.gz` 文件。最后,删除原始文件夹。 还原脚本: ``` #!/bin/bash # MongoDB restore script # MongoDB credentials user="username" password="password" host="localhost" port="27017" db_name="database_name" # Other options backup_path="/path/to/backup/folder" filename="$db_name-$date.tar.gz" # Restore command tar -zxvf $backup_path/$filename -C $backup_path mongorestore --host=$host --port=$port --username=$user --password=$password --db=$db_name $backup_path/$db_name-$date/$db_name ``` 在还原脚本中,您需要使用与备份脚本相同的 `username`、`password`、`host` 和 `database_name` 值。`backup_path` 变量应该与备份脚本中的相同。`filename` 变量包含备份文件名,它必须与备份脚本中的相同。 还原期间,`tar` 命令将备份文件解压缩到指定的文件夹中。然后使用 `mongorestore` 命令将备份数据还原到数据库中。 请注意,这些脚本仅是示例,不适用于所有情况。在实际使用之前,请测试并根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值