MongoDB 基础系列十一:mongo Shell 配置

前言

此篇博文是 Mongdb 基础系列之一;

本文为作者的原创作品,转载需注明出处;

自定义 Prompt

通过在 mongo shell 中修改 prompt 变量信息来自定义 prompt 输出;prompt 变量可以像 javascript 代码那样保存 strings 变量;同样的 prompt 可以保存一个 function 来动态的显示不同的信息;

你可以通过 .mongorc.js 文件来定义 prompt 变量以便每次启动 mongo shell 的时候都会自动加载这些变量;

自定义 Prompt 来显示操作的数量

For example,to create a mongo shell prompt with the number of operations issued in the current session, define the following variables in the mongo shell:

1
2
3
4
cmdCount = 1;
prompt = function() {
return (cmdCount++) + "> ";
}

The prompt would then resemble the following:

1
2
3
1>
2>
3>

自己亲自试验了一把,直接将上面的 prompt 的代码在 mongo shell 中输入,就会得到此效果,

可见,一旦定义好了 prompt 变量以后,输入命令行便发生了变化;以数字>的格式进行显示了;

TODO,试验在 .mongorc.js 中预定义好 prompt 相关的代码,这样就不用每次在命令行中输入了;

自定义 Prompt 来显示 Database 和 Hostname

1
2
3
4
5
host = db.serverStatus().host;

prompt = function() {
return db+"@"+host+"$ ";
}

在命令行输入以后,显示

1
test@myHost1$

test 既是当前 database 的名字,myHost1 既是当前主机的 Hostname;

自定义 Prompt 来显示 Up Time 和 Document 统计信息

1
2
3
prompt = function() {
return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > ";
}

执行以后,

1
Uptime:5897 Documents:6 >

在 mongo shell 中使用外部编辑器

正如前文中 Multi-line Operations in the mongo Shell 中所描述的那样,在 mongo shell 中编写 javascript function 非常的不方便,而且如果在编写的过程当中出现错误,不能回退到上一行当中,相当的麻烦;正是因为这个原因,所以 mongo shell 提供了使用外部编辑器的方式来弥补这个缺陷;

首先,设置环境变量,设置 EDITOR 为 vim;

1
$ export EDITOR=vim

注意,上述的环境变量的设置方式只在当前的命令行中有效;

再次,进入 mongo shell

1
2
3
$ mongo
...
>

然后,创建一个 Function myFunction

1
> function myFunction(){ }

然后,使用 edit 命令进行编辑

1
> edit myFunction

然后,神奇的事情便发生了,我们开始使用我们所熟悉的 vim 来编辑方法 myFunction 了;如图,

编辑好以后,保存退出;

最后,检查一下修改后的结果,

1
2
3
> myFunction
function myFunction(){
console.log("hello world!")

修改 mongo shell 的 batch size

The db.collection.find() method is the JavaScript method to retrieve documents from a collection. The db.collection.find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Type it to iterate another 20 times.

You can set the DBQuery.shellBatchSize attribute to change the number of documents from the default value of 20, as in the following example which sets it to 10:

1
> DBQuery.shellBatchSize = 10;

References

https://docs.mongodb.com/manual/tutorial/configure-mongo-shell/