连接指定数据库
 .\mongosh.exe localhost:27017/test
 

不连接数据库
 .\mongosh.exe --nodb
 
然后连接数据库
conn = new Mongo("localhost:27017")
/// mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000
db = conn.getDB("test")
 

shell使用技巧
查看帮助
 
 
 
 了解具体方法怎么用
 
执行脚本
新建s1.js和s2.js
print("我是第一个脚本")
print("我是第二个脚本")
 
运行
.\mongosh.exe .\s1.js .\s2.js
 

 如果使用连接到非默认主机/端口上的 mongod 实例运行脚本,则需要先指定地址,之后再指定脚本
.\mongosh.exe localhost:30000/test --quiet s1.js s2.js
 
–quiet 选项来防止打印打印其他信息
load运行脚本

 shell辅助函数对应的JavaScript函数
| shell函数 | js函数 | 
|---|---|
| use test | db.getSisterDB(“test”) | 
| show dbs | db.getMongo().getDBs() | 
| show collections | db.getCollectionNames() | 
| 新建connect.js | 
var connectionTo = function(port,dbname){
	if(!port){
		port = 27017;
	}
	if(!dbname){
		dbname="test";
	}
	db = connect("localhost:"+port+"/"+dbname)
	return db;
}
 

.mongorc.js
如果你有一些需要频繁被加载的脚本,那么可以将它们添加到 .mongoshrc.js 文件中。此文件会在启动 shell 时自动运行。
 
再mongoshrc下添加如下代码
print("from mongorc")
 

 可以在.mongoshrc.js中禁用"危险"函数
var no = function(){
    print("函数被禁用")
}
// 禁止删除数据库
db.dropDatabase = db.prototype.dropDatabase=no;
// 禁止删除集合
DBCollection.prototype.drop = no;
// 禁止删除索引
DBCollection.prototype.dropIndex = no;
// 禁止删除多个索引
DBCollection.prototype.dropIndexes = no;
//新版
// 禁止删除数据库
db.dropDatabase = db.prototype.dropDatabase=no;
// 禁止删除集合
//DBCollection.prototype.drop = no;
db.collection.prototype.drop = no;
// 禁止删除索引
// DBCollection.prototype.dropIndex = no;
db.collection.prototype.dropIndex = no;
// 禁止删除多个索引
// DBCollection.prototype.dropIndexes = no;
db.collection.prototype.dropIndexes = no;
 
如果在启动 shell 时指定 --norc 参数,则可以禁用对 .mongorc.js 文件的加载。
定制shell提示信息
/**
 * 显示当前时间
 */
prompt = function(){
    return (new Date())+" >:";
}
/**
 * 显示当前数据库
 */
prompt = function(){
    if(typeof db === "undefined"){
        return "(nodb)>"
    }
    try{
        db.runCommand({getLastError:1})
    }catch(e){
        print(e)
    }
    return db+">"
}
 

编辑复杂变量
如果要编辑一个变量,可以使用 edit varname 命令
var student = db.students.findOne({name:"小明"})
edit student
 
完成更改后,保存并退出编辑器。变量将被重新解析并加载回 shell
 将 EDITOR=“/path/to/editor”; 添加到 .mongorc.js 文件中,以后就不用再设置此变量了。
不便使用的集合名称
var name ="@#%";
db[name].find()
                

















