The mongo Shellmongo

On this page本页内容

The mongo shell is an interactive JavaScript interface to MongoDB. mongoShell是MongoDB的交互式JavaScript接口。You can use the mongo shell to query and update data as well as perform administrative operations.您可以使用mongoshell查询和更新数据以及执行管理操作。

Note

The following document pertains to the mongo shell included in the MongoDB Server Download. 以下文档涉及MongoDB服务器下载中包含的mongoshell。For information on the new MongoDB Shell, mongosh, refer to the mongosh Documentation.有关新MongoDB外壳mongosh的信息,请参阅mongosh文档

To understand the differences between the two shells, see Comparison of the mongo Shell and mongosh.要了解这两种外壳之间的差异,请参阅mongo外壳和mongosh外壳的比较

Download the mongo Shell下载mongo Shell

The mongo shell is included as part of the MongoDB server installation. If you have already installed the server, the mongo shell is installed to the same location as the server binary.

Alternatively, if you would like to download the mongo shell separately from the MongoDB Server, you can install the shell as a standalone package by following these steps:

  1. Access the Download Center for your Edition of MongoDB:访问您的MongoDB版本的下载中心:

  2. Select your preferred Version and Platform from the dropdowns.从下拉列表中选择您的首选版本和平台。
  3. Select the Package to download according to your platform:根据您的平台选择要下载的软件包:

    Platform平台Download Package下载包
    Windows Select the zip package to download an archive which includes the mongo shell.选择zip包下载包含mongo shell的归档文件。
    macOS Select the tgz package to download an archive which includes the mongo shell.
    Linux Select the tgz package to download the mongo shell.
  4. Copy the mongo shell from the archive to a location on your filesystem.

Start the mongo Shell and Connect to MongoDB启动mongo Shell并连接到MongoDB

Once you have downloaded the mongo shell, you can use it to connect to your running MongoDB server.下载mongoShell后,可以使用它连接到正在运行的MongoDB服务器。

Note

Starting in MongoDB 4.2 (and 4.0.13), the mongo shell displays a warning message when connected to non-genuine MongoDB instances as these instances may behave differently from the official MongoDB instances; e.g. missing or incomplete features, different feature behaviors, etc.

Prerequisites先决条件

  • The MongoDB server must be installed and running before you can connect to it from the mongo shell. Follow the steps in the installation tutorial for your platform to install and start the MongoDB server if required.
  • Once you have verified that the mongod server is running, open a terminal window (or a command prompt for Windows) and go to your <mongo shell installation dir> directory:

    cd <mongo shell installation dir>

    Tip

    Adding your <mongo shell installation dir> to the PATH environment variable allows you to type mongo directly instead of having to first go to the <mongo shell installation dir> directory or specify the full path to the binary. Alternatively, you can copy the mongo shell to a location on your filesystem that is already present in your PATH, such as /usr/bin on Linux.

Local MongoDB Instance on Default Port默认端口上的本地MongoDB实例

You can run mongo shell without any command-line options to connect to a MongoDB instance running on your localhost with default port 27017:

mongo

Local MongoDB Instance on a Non-default Port非默认端口上的本地MongoDB实例

To explicitly specify the port, include the --port command-line option. For example, to connect to a MongoDB instance running on localhost with a non-default port 28015:

mongo --port 28015

MongoDB Instance on a Remote Host远程主机上的MongoDB实例

To explicitly specify the hostname and/or port,要明确指定主机名和/或端口,

  • You can specify a connection string. For example, to connect to a MongoDB instance running on a remote host machine:

    mongo "mongodb://mongodb0.example.com:28015"
  • You can use the command-line option --host <host>:<port>. For example, to connect to a MongoDB instance running on a remote host machine:

    mongo --host mongodb0.example.com:28015
  • You can use the --host <host> and --port <port> command-line options. For example, to connect to a MongoDB instance running on a remote host machine:

    mongo --host mongodb0.example.com --port 28015

MongoDB Instance with Authentication具有身份验证的MongoDB实例

To connect to a MongoDB instance requires authentication:要连接到MongoDB实例,需要进行身份验证:

  • You can specify the username, authentication database, and optionally the password in the connection string. For example, to connect and authenticate to a remote MongoDB instance as user alice:

    Note

    If you do not specify the password in the connection string, the shell will prompt for the password.

    mongo "mongodb://alice@mongodb0.examples.com:28015/?authSource=admin"
  • You can use the --username <user> and --password, --authenticationDatabase <db> command-line options. For example, to connect and authenticate to a remote MongoDB instance as user alice:

    Note

    If you specify --password without the user’s password, the shell will prompt for the password.

    mongo --username alice --password --authenticationDatabase admin --host mongodb0.examples.com --port 28015

Connect to a MongoDB Replica Set连接到MongoDB副本集

To connect to a replica set:要连接到副本集,请执行以下操作:

  • You can specify the replica set name and members in the connection string.

    mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"
  • If using the DNS Seed List Connection Format, you can specify the connection string:

    mongo "mongodb+srv://server.example.com/"

    Note

    Use of the +srv connection string modifier automatically sets the ssl option to true for the connection.

  • You can specify the replica set name and members from the --host <replica set name>/<host1>:<port1>,<host2>:<port2>,... command-line option. For example, to connect to replica set named replA:

    mongo --host replA/mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017

TLS/SSL ConnectionTLS/SSL连接

For TLS/SSL connections,

  • You can specify the ssl=true option in the connection string.

    mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA&ssl=true"
  • If using the DNS Seed List Connection Format, you can include the +srv connection string modifier:

    mongo "mongodb+srv://server.example.com/"

    Note

    Use of the +srv connection string modifier automatically sets the ssl option to true for the connection.

  • You can specify --ssl command-line option. For example, to connect to replica set named replA:

    mongo --ssl --host replA/mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017

See also参阅

For more information on the options used in the connection examples as well as other options, see mongo reference and examples of starting up mongo.

Working with the mongo Shell

To display the database you are using, type db:要显示正在使用的数据库,请键入db

db

The operation should return test, which is the default database.

To switch databases, issue the use <db> helper, as in the following example:

use <database>

See also db.getSiblingDB() method to access a different database from the current database without switching your current database context (i.e. db).

To list the databases available to the user, use the helper show dbs. [1]

You can switch to non-existing databases. When you first store data in the database, such as by creating a collection, MongoDB creates the database. For example, the following creates both the database myNewDatabase and the collection myCollection during the insertOne() operation:

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

The db.myCollection.insertOne() is one of the methods available in the mongo shell.

If the mongo shell does not accept the name of a collection, you can use the alternative db.getCollection() syntax. For instance, if a collection name contains a space or hyphen, starts with a number, or conflicts with a built-in function:

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

The mongo shell prompt has a limit of 4095 codepoints for each line. If you enter a line with more than 4095 codepoints, the shell will truncate it.

For more documentation of basic MongoDB operations in the mongo shell, see:

[1]If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.

Format Printed Results打印结果的格式

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.

To format the printed result, you can add the .pretty() to the operation, as in the following:

db.myCollection.find().pretty()

In addition, you can use the following explicit print methods in the mongo shell:此外,您可以在mongo shell中使用以下显式打印方法:

  • 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>))

For more information and examples on cursor handling in the mongo shell, see Iterate a Cursor in the mongo Shell. See also Cursor Help for list of cursor help in the mongo shell.

Multi-line Operations in the mongo Shellmongo Shell中的多行操作

If you end a line with an open parenthesis ('('), an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')'), the closing brace ('}') or the closing bracket (']'). The mongo shell waits for the closing parenthesis, closing brace, or the closing bracket before evaluating the code, as in the following example:

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

You can exit the line continuation mode if you enter two blank lines, as in the following example:如果输入两个空行,则可以退出行继续模式,如下例所示:

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

Tab Completion and Other Keyboard Shortcuts制表符完成和其他键盘快捷键

The mongo shell supports keyboard shortcuts. For example,例如

For a full list of the shortcuts, see Shell Keyboard Shortcuts

.mongorc.js File

When starting, mongo checks the user’s HOME directory for a JavaScript file named .mongorc.js. If found, mongo interprets 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 mongo, mongo 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.

Exit the Shell

To exit the shell, type quit() or use the <Ctrl-C> shortcut.

Comparison of the mongo Shell and mongosh

Note

mongosh is currently available as a Beta release. The product, its features, and the corresponding documentation may change during the Beta stage.在测试阶段,产品、其功能和相应的文档可能会发生更改。

The new MongoDB Shell, mongosh, offers numerous advantages over the mongo shell, such as:

During the beta stage, mongosh supports a subset of the mongo shell methods. Achieving feature parity between mongosh and the mongo shell is an ongoing effort.

To maintain backwards compatibility, the methods that mongosh supports use the same syntax as the corresponding methods in the mongo shell. To see the complete list of methods supported by mongosh, see MongoDB Shell Methods.

See also参阅