MongoDB 官方文档学习笔记(三):The Mongo shell

The Mongo Shell

介绍

Mongo shell 是MongoDB交互式JavaScript接口。可以通过mongo shell 查询,更新MongoDB数据,也可以进行管理操作。

The mongo shell is a component of the MongoDB distributions. Once you have installed and have started MongoDB, connect the mongo shell to your running MongoDB instance.

启动mongo shell

启动mongo shell 连接 通过localhost 和 默认端口启动的MongoDB实例:

  1. 进入MongoDB安装路径
cd <mongodb installation dir>

    2. 输入./bin/mongo启动mongo

./bin/mongo

若已经将MongoDB安装路径添加至系统环境变量,则可以直接通过输入mongo启动mongo。

Options

When you run mongo without any arguments, the mongo shell will attempt to connect to the MongoDB instance running on the localhost interface on port 27017. To specify a different host or port number, as well as other options, see examples of starting up mongo and mongo reference which provides details on the available options.

.mongorc.js File

When starting, mongo checks the user’s HOME directory for a JavaScript file named .mongorc.js. If found, mongointerprets the content of .mongorc.js before displaying the prompt for the first time. If you use the shell to evaluate a JavaScript file or expression, either by using the --eval option on the command line or by specifying a .js file to mongomongo will read the .mongorc.js file after the JavaScript has finished processing. You can prevent .mongorc.js from being loaded by using the --norc option.

mongo shell 操作

显示数据库,输入db:

db

默认返回test,即,MongoDB的默认数据库。使用 use <db>切换数据库:

use <database>

列出所有可用的数据库,也可以通过db.getSiblingDB() 方法不切换数据库访问其他数据库

show dbs

可以切换至不存在的数据库,当你首次插入数据的时候讲创建数据库及集合。

use myNewDatabase
db.myCollection.insertOne( { x: 1 } );

 db.myCollection.insertOne() mongo shell 的可用方法:

  • db 表示当前数据库;
  • myCollection 表示当前集合;

当集合名字存在空格、以数字开头或者和内建函数同名而无法通过db使用点号访问时,可以通过db.getCollection()方法获取当前数据库集合:

db.getCollection("3 test").find()
db.getCollection("3-test").find()
db.getCollection("stats").find()

mongo shell 一行最多4095个码点(codepoint),超过将会被截断;

更多的基于mongo shell的文档操作可以参考:

格式化打印结果

db.collection.find()方法将返回查询结果的游标(cursor)。

若返回的游标未指向可用的结果集时,mongo sh 将自动重试20次,以获取查询的前20条文档。

格式化查询结果为易读的,可加上.pretty()操作:

db.myCollection.find().pretty()

此外还可以通过其他格式化操作:

  • print() to print without formatting
  • print(tojson(<obj>)) to print with JSON formatting and equivalent to printjson()
  • printjson() to print with JSON formatting and equivalent to print(tojson(<obj>))


shell多行操作

若行结束字符为括号"(", 花括号"{",中括号“[”,那么子句将以 “...”开始,直到键入对应的闭合括号")", 花括号"}",中括号“]”。如:

> if ( x > 0 ) {
... count++;
... print (x);
... }

可以通过连续的两个空行退出子句;

> if (x > 0
...
...
>

Tab键补全及快捷键

  • 通过Tab键可以补全输入;
  • 通过上下箭头可选择历史命令;
db.myCollection.c<Tab>

补全c开头的方法等;

退出mongo shell

可以键入quit()或者使用<Ctrl-C>快捷键退出mongo shell。





猜你喜欢

转载自blog.csdn.net/zhujq_icode/article/details/81053411