mongodb 脚本

Write Scripts for the mongo Shell — MongoDB Manual

Shell HelpersJavaScript Equivalents
show dbsshow databases
db.adminCommand('listDatabases')
use <db>
db = db.getSiblingDB('<db>')
show collections
 
db.getCollectionNames()
show users
 
db.getUsers()
show roles
 
db.getRoles({showBuiltinRoles: true})
show log <logname>
 
db.adminCommand({ 'getLog' : '<logname>' })
show logs
 
db.adminCommand({ 'getLog' : '*' })
it
 
cursor = db.collection.find()
if ( cursor.hasNext() ){
   cursor.next();
}

EXAMPLE

To print all items in a result cursor in mongo shell scripts, use the following idiom:

cursor = db.collection.find();
while ( cursor.hasNext() ) {
   printjson( cursor.next() );
}

forEach:

db.collection.find().forEach(<function>)
db.restaurants.find().forEach( function(myDoc) { print( "name: " + myDoc.name ); } );

 执行脚本的3中方法

1.  --eval

mongo test --eval "printjson(db.getCollectionNames())"

2.Execute a JavaScript file

mongo localhost:27017/test myjsfile.js

 有帐号密码的方式

mongo user:passwd@ip:27017/dbname  dropreceive.sh >/root/mongoshell/drop.log

 或者在js脚本中

db = db.getSiblingDB('xxx');
db.auth('user','passwd');

3. load:You can execute a .js file from within the mongo shell, using the load() function

load("myjstest.js")

报错:    malformed UTF-8 character sequence at offset

问题原因:插入的数据中存在字符编码问题

js文件打开,转码程utf-8 就可以

练习:

批量删除receive库中所有collection 的数据

my.js

db = db.getSiblingDB('receive')
c = db.getCollectionNames();
c.forEach(function(value, index, array){
    print(value);
  db.getCollection(value).remove({});
})

在mongo 的shell中执行load('path/my.js')

练习: 通过聚合搜索出重复的数据,把重复数据保存到文件中

dd.js 

dumpcursor = db.getCollection('ProductDev_version').aggregate([
  {$match:{
      "daas.status":"1"
      }},
 {$match:{$or:
    [
         {"data.product_organ_code":"0000"},
         {"data.product_organ_code":{$exists:false}}
   ]}},
 {$group:{_id:{"relversion":"$data.relversion"},count:{$sum:1}}},
 {$match:{count:{$gt:1}}}
 ]
 ,{ allowDiskUse: true });
 
 while(dumpcursor.hasNext()){
     d1 = dumpcursor.next();
     v1 = d1._id.relversion;
     vercursor = db.getCollection('ProductDev_version').find({"daas.status":"1",'data.relversion':v1,$or:
    [
         {"data.product_organ_code":"0000"},
         {"data.product_organ_code":{$exists:false}}
   ]
   },{"metadata.id":1,"metadata.systemtag":1,"metadata.source":1,"metadata.businessObject":1,"data.relversion":1,"data.ec_serial_no":1});
   while(vercursor.hasNext()){
       v2 = vercursor.next();
       printjsononeline(v2)
   }
   
 }
 

执行:

mongo ip:27017/dbname dd.js >1.txt

删除重复的记录数:

坑: 必须用 foreach,不能有游标,否则有问题

db = db.getSiblingDB('xxx')
db.getCollection('xxxxxx').aggregate([
{$group:{"_id":{"metadataid":"$metadata.id","metadatasystemtag":"$metadata.systemtag"},count:{$sum:1}}},
{$match:{count:{$gt:1}}}
],{ allowDiskUse: true }).forEach(function(dd){
    printjson(dd);
    ddmetaid = dd._id.metadataid;
    ddsystag=dd._id.metadatasystemtag;
    i=1;
    db.getCollection('xxxxxx').aggregate([
    {$match:{"metadata.id":ddmetaid,"metadata.systemtag":ddsystag}},
    {$sort:{"metadata.timestamp":-1}}
    ]).forEach(function(dd2){
        if(i!=1){
            dd2metaid=dd2.metadata.id;
        dd2metatag=dd2.metadata.systemtag;
        dd2timestamp=dd2.metadata.timestamp;
        db.getCollection('xxxxxx').remove({"metadata.id":dd2metaid,"metadata.systemtag":dd2metatag,"metadata.timestamp":dd2timestamp});

        }
        i++;
        })
    })
    

    
    

以下是 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` 命令将备份数据还原到数据库中。 请注意,这些脚本仅是示例,不适用于所有情况。在实际使用之前,请测试并根据需要进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值