Write Scripts for the mongo Shell — MongoDB Manual
Shell Helpers | JavaScript Equivalents |
---|---|
show dbs , show databases | |
| |
| |
| |
| |
| |
| |
| |
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++;
})
})