mongodb shell

连接指定数据库

 .\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 testdb.getSisterDB(“test”)
show dbsdb.getMongo().getDBs()
show collectionsdb.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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值