https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
Shell Helpers | JavaScript Equivalents |
---|---|
show dbs , show 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
3. load:You can execute a .js
file from within the mongo
shell, using the load()
function
load("myjstest.js")
练习:
批量删除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')